我很早学过,只是当时没有系统记录笔记,导致过一段时就容易忘记很多东西。本笔记主要参考JavaScript 基础-千古前端图文教程,mdn web docs - JavaScript
Web 前端有三层:
- HTML:从语义的角度,描述页面结构
- CSS:从审美的角度,描述样式(美化页面)
- JavaScript(简称 JS):从交互的角度,描述行为(实现业务逻辑和页面控制)
H1Date
H2Date() constructor
The Date()
constructor can create a Date
instance or return a string representing the current time.
const date1 = new Date()
H2getFullYear()
The getFullYear()
method returns the year of the specified date according to local time.
H2getMonth()
The getMonth()
method returns the month on the specified date according to local time, as a zero-based value (where zero indicates the first month of the year).
H2getDate()
The getDate()
method returns the day of the month for the specified date according to local time.(几号)
H2getDay()
The getDay()
method returns the day of the week for the specified date according to local time, where 0 represents Sunday. (周几)
H2getHours()
The getHours()
method returns the hour for the specified date, according to local time.
H2getMinutes()
The getMinutes()
method returns the minutes on the specified date according to local time.
H2getSeconds()
The getSeconds()
method returns the seconds in the specified date according to local time.
H2getTime()
The getTime()
method returns the number of milliseconds since the epoch, which is defined as the midnight at the beginning of January 1, 1970, UTC.
H1Math
H2Methods
H3abs()
The Math.abs()
static method returns the absolute value of a number.
H3ceil()
The Math.ceil()
static method always rounds up and returns the smaller integer greater than or equal to a given number.
H3floor()
The Math.floor()
static method always rounds down and returns the largest integer less than or equal to a given number.
H3max() & min()
Note:
Math.max(...aaray1)
. We should use spread syntax.
H3pow()
Recommend:
2 ** 3 = 8
H3random()
Math.floor(Math.random() * y + x)
👉 [x, y) 区间的随机整数
Math.ceil(Math.random() * y + x)
👉 (x, y] 区间的随机整数
Math.round(Math.random() * y + x)
👉 [x, y] 区间的随机整数
H3round()
The Math.round()
static method returns the value of a number rounded to the nearest integer.
H1Array
H2Properties
H3length
The length
property of an Array
object represents the number of elements in that array. The value is an unsigned, 32-bit integer that is always numerically greater than the highest index in the array.
Try it:
H2Methods
H3at()
The at()
method of Array instances takes an integer value and returns the item at that index, allowing for positive and negative integers. Negative integers count back from the last item in the array.
H3concat()
The concat()
method is used to merge two or more arrays. This method does not change the existing arrays but returns a new array.
其实**扩展语法(spread syntax)**更好:
使用扩展语法可以使代码更简洁易读,而且性能也比使用
concat()
方法更好
H3every()
The every()
method tests whether all elements in the array pass the test implemented by the provided function. It returns a Boolean value.
人话说就是如果所有元素满足条件,就返回 true,反之。
H3map()
The map()
method of Array instances creates a new array populated with the results of calling a provided function on every element in the calling array.
H3includes()
includes()
方法用来判断一个数组是否包含某特定值,返回 boolean 值。
H3indexOf()
The indexOf()
method returns the first index at which a given element can be found in the array, or -1 if it is not present.
H3isArray()
The Array.isArray()
static method determines whether the passed value is an Array
.
H3⭐️filter()
The filter()
method creates a shallow copy of a portion of a given array, filtered down to just the elements from the given array that pass the test implemented by the provided function.
人话说就是返回满足条件的元素新数组。
filter()
可以用来移除数组里对应值的元素。返回一个新数组,条件设为不等于某个值即可。
H3find()
The find()
method returns the first element in the provided array that satisfies the provided testing function. If no values satisfy the testing function, undefined
is returned.
人话说就是返回第一个满足条件的元素。
H3findIndex()
The findIndex()
method returns the index of the first element in an array that satisfies the provided testing function. If no elements satisfy the testing function, -1 is returned.
H3flat()
The flat()
method of Array instances creates a new array with all sub-array elements concatenated into it recursively up to the specified depth.
H3forEach()
The forEach()
method executes a provided function once for each array element.
H3from()
The Array.from()
static method creates a new, shallow-copied Array instance from an iterable or array-like object.
H3join()
The join()
method creates and returns a new string by concatenating(连接) all of the elements in an array (or an array-like object), separated by commas or a specified separator string. If the array has only one item, then that item will be returned without using the separator.
H3push()
The push()
method adds one or more elements to the end of an array and returns the new length of the array.
H3⭐️reduce()
reduce()
方法对数组中的每个元素按序执行一个由您提供的 reducer 函数,每一次运行 reducer 会将先前元素的计算结果作为参数传入,最后将其结果汇总为单个返回值。
Syntax:
Example:
第一次执行回调函数时,不存在“上一次的计算结果”。如果需要回调函数从数组索引为 0 的元素开始执行,则需要传递初始值。否则,数组索引为 0 的元素将被作为初始值 initialValue,迭代器将从第二个元素开始执行(索引为 1 而不是 0)。
H3reduceRight()
From right-to-left.
H3reverse()
reverse()
方法将数组中元素的位置颠倒,并返回该数组。数组的第一个元素会变成最后一个,数组的最后一个元素变成第一个。该方法会改变原数组。
H3shift()
The shift()
method of Array instances removes the first element from an array and returns that removed element. This method changes the length of the array.
H3slice()
slice()
方法返回一个新的数组对象,这一对象是一个由 begin
和 end
决定的原数组的浅拷贝(包括 begin
,不包括end
)。原始数组不会被改变。(左闭右开)
H3some()
The some()
method tests whether at least one element in the array passes the test implemented by the provided function.
人话说就是如果至少有一个元素满足条件,就返回 true,反之。
H3sort()
The default sort order is ascending.
Syntax:
The compareFn
return value should be a number that indicates the relative order of the two elements. Let's say a
& b
. Descending if b - a
, ascending if a - b
.
H3⭐️splice()
The splice()
method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place.
Return value:
An array containing the deleted elements.
If only one element is removed, an array of one element is returned.
If no elements are removed, an empty array is returned.
Syntax:
start
: Zero-based index at which to start changing the array.
H3toSorted()
The toSorted()
method of Array instances is the copying version of the sort()
method. It returns a new array with the elements sorted in ascending order.
H3unshift()
The unshift()
method adds one or more elements to the beginning of an array and returns the new length of the array.
H1Object
H2Methods
H3keys() & values()
Object.keys()
方法会返回一个由一个给定对象的自身可枚举属性组成的数组,数组中属性名的排列顺序和正常循环遍历该对象时返回的顺序一致。
H3entries()
H1String
H2Properties
H3length
The length
method returns the length of a specified string.
Note: The length of an empty string is 0.
Try it:
H2Methods
H3charCodeAt()
The charCodeAt()
method of String
values returns an integer between 0
and 65535
representing the UTF-16 code unit at the given index.
Try it:
H3fromCharCode()
The String.fromCharCode()
static method returns a string created from the specified sequence of UTF-16 code units.
Try it:
H3lastIndexOf()
lastIndexOf()
方法返回调用 String 对象的指定值最后一次出现的索引,在一个字符串中的指定位置 fromIndex
处从后向前搜索。如果没找到这个特定值则返回 -1。
Syntax: str.lastIndexOf(searchValue[, fromIndex])
searchValue
: 一个字符串,表示被查找的值。
fromIndex
(可选): 待匹配字符串 searchValue 的开头一位字符从 str 的第 fromIndex 位开始向左回向查找。fromIndex
默认值是 +Infinity
。如果 fromIndex >= str.length
,则会搜索整个字符串。如果 fromIndex < 0
,则等同于 fromIndex == 0
。
H3slice()
The slice()
method extracts a section of a string and returns it as a new string, without modifying the original string.
Try it:
H3substring()
The substring()
method returns the part of the string
between the start and end indexes, or to the end of the string.(用法和slice()
相似,看例子知用法)
Try it:
H3split()
The split()
method takes a pattern and divides a String into an ordered list of substrings by searching for the pattern, puts these substrings into an array, and returns the array.
Try it:
H3startsWith()
The startsWith()
method determines whether a string begins with the characters of a specified string, returning true
or false
as appropriate.
Syntax:
searchString
: The characters to be searched for at the start of this string. Cannot be a regex(正则表达式).
position
(optional): The start position at which searchString
is expected to be found (the index of searchString
's first character). Defaults to 0
.
Try it:
H3endsWith()
The endsWith()
method determines whether a string ends with the characters of a specified string, returning true
or false
as appropriate.(用法和starsWith()
相似,不多说)
Try it:
H3padEnd()
Same as below
H3padStart()
The padStart()
method of String values pads this string with another string (multiple times, if needed) until the resulting string reaches the given length. The padding is applied from the start of this string.
H3toLowerCase() & toUpperCase()
The toLowerCase()
method returns the calling string value converted to lower case.
H3trim()
The trim()
method removes whitespace from both ends of a string and returns a new string, without modifying the original string.
H3repeat()
The repeat()
method of String values constructs and returns a new string which contains the specified number of copies of this string, concatenated together.
H3replace()
replace()
根据规则将字符串中某部分替换成新内容,并返回新字符串。
语法:replace(substr|regexp, newSubStr|function)
第一个参数是要被替换的老字符串,或者正则表达式,记得用斜线 / 围上,后面可以加 g 或者 i 或者 gi,代表全局匹配、忽略大小写。
第二个参数是新字符串,或者函数,该函数返回着将替换掉第一个参数匹配到对结果。
H1Number
H2Methods
H3toFixed()
H3toLocaleString()
toLocaleString()
方法返回这个数字在特定语言环境下的表示字符串
Syntax: toLocaleString([locales, options])
locales
和 options
参数让应用程序可以指定要进行格式转换的语言,并且定制函数的行为。
常用的就是将数字每三个数位用逗号分隔开
H3toString()
The toString()
method of Number values returns a string representing this number value.
H1Set
Set
objects are collections of values. A value in the set may only occur once;
Note: you can put
String
andArray
inSet()
to turn intoSet
.
Set vs Array:
Array:
- Pros:
- Allows accessing elements by index with a time complexity of O(1).
- Maintains the insertion order of elements.
- Cons:
- Searching for specific elements may be less efficient, requiring traversing the entire array.
- Adding or removing elements may require shifting other elements, leading to performance degradation.
Set:
- Pros:
- Does not allow duplicate elements, automatically deduplicates, suitable for storing unique values.
- Supports efficient lookup operations with a time complexity of O(1).
- Supports efficient adding and removing operations with an average time complexity of O(1).
- Cons:
- Does not support accessing elements by index since sets are unordered.
- Does not maintain the insertion order of elements.
The choice between Array and Set depends on your specific requirements:
- If you need to store an ordered collection with possibly duplicate elements, you can use an Array.
- If you need to store unique values or require efficient lookup, addition, and removal operations, a Set should be used.
H2Properties
H3size
Like length
.
H2Methods
H3add()
The add()
method of Set
instances inserts a new element with a specified value in to this set, if there isn't an element with the same value already in this set.
H3delete()
The delete()
method of Set
instances removes a specified value from this set, if it is in the set.
H3values()
Set -> Array:
[…set.values()]
is equivalent to[...set]
H1Map
The Map
object holds key-value pairs and remembers the original insertion order of the keys. Any value (both objects and primitive values) may be used as either a key or a value.
Map vs Object:
- Key type: The keys of Object can only be string or Symbol types, while the keys of Map can be of any type, including basic data types, objects, functions, etc.
- Number of key-value pairs: The number of key-value pairs of Object is not easy to obtain directly and needs to be calculated manually, while the number of key-value pairs of Map can be obtained directly through the size attribute.
- Iteration order: There is no order guarantee for the properties of Object, and the order of key-value pairs cannot be guaranteed when traversing, while Map will maintain the insertion order.
- Performance: In scenarios where key-value pairs are frequently added or deleted, Map may perform better than Object.
H2Properties
H3size
Like length
.
H2Methods
H3has()
The has()
method of Map instances returns a boolean indicating whether an element with the specified key exists in this map or not.
H3values()
H1BigInt
BigInt
values represent numeric values which are too large to be represented by the number primitive.
H1Built-in Objects
H2parseInt()
The parseInt()
function parses a string argument and returns an integer of the specified radix (the base in mathematical numeral systems).
H1Document
H2Methods
H3querySelector()
The Document
method querySelector()
returns the first Element
within the document that matches the specified selector, or group of selectors. If no matches are found, null
is returned.
例如:
const el = document.querySelector(".myclass");
H3querySelectorAll()
The Document method querySelectorAll()
returns a static (not live) NodeList
representing a list of the document's elements that match the specified group of selectors.
例如:
后者是返回所有满足 .note 或者 .alert 的元素列表
H1Element
H2Properties
H3innerHTML
The Element
property innerHTML
gets or sets the HTML or XML markup contained within the element.
H4get HTML
Reading innerHTML
causes the user agent to serialize the HTML or XML fragment comprised of the element's descendants. The resulting string is returned.
let contents = element.innerHTML;
H4set HTML
element.innerHTML = contents;
H3innerText
innerText
属性表示一个节点及其后代的“渲染”文本内容。
H4get Text
let text = element.innerText;
H4set Text
element.innerText = text
H3textContent
DITTO
但 textContent
和 innerText
区别是:
innerText
属性是一个非标准属性,它返回元素及其子元素中的渲染文本内容,它不考虑样式的影响并忽略空白符号。由于这个属性是非标准的,因此不是所有浏览器都支持它,也可能在将来被废弃。
textContent
属性返回元素及其子元素中的所有文本内容,包括空白字符和隐藏元素中的文本,但不考虑样式的影响。这个属性在所有现代浏览器中都得到支持,并且是标准属性。
H1Window
H2Properties
H3scrollY
The read-only scrollY
property of the Window
interface returns the number of pixels that the document is currently scrolled vertically.
Syntax: window.scrollY
H3scrollX
DITTO
H3innerHeight
The read-only innerHeight
property of the Window
interface returns the interior height of the window in pixels, including the height of the horizontal scroll bar, if present.
H3innerwidth
DITTO
H3localStorage
The localStorage read-only property of the window interface allows you to access a Storage object for the Document's origin; the stored data is saved across browser sessions.
localStorage
is similar to sessionStorage, except that while localStorage
data has no expiration time, sessionStorage
data gets cleared when the page session ends — that is when the page is closed. (localStorage
data for a document loaded in a "private browsing" or "incognito"(无痕浏览) session is cleared when the last "private" tab is closed.)
H4setItem()
The following snippet accesses the current domain's local Storage object and adds a data item to it using Storage.setItem().
Note:
value must be a string, so if you have a complex value like an array or object to save, you'll need to use:
JSON.stringify(value)
It can turn that array or object into a stringified version or rather a JSON version that can be saved in local storage.
On the contrary, we can use
JSON.parse()
to turn the stringified array back into a real JS array.
H4getItem()
The syntax for reading the localStorage
item is as follows:
let cat = JSON.parse(localStorage.getItem('key'));
H4removeItem()
The syntax for removing the localStorage
item is as follows:
localStorage.removeItem('key');
H4clear()
The syntax for removing all the localStorage
items is as follows:
localStorage.clear();
H3sessionStorage
同上
H2Methods
H3setInterval()
The setInterval()
method calls a function at specified intervals (in milliseconds).
The setInterval()
method continues calling the function until clearInterval()
is called, or the window is closed.
Syntax: setInterval(function, milliseconds, param1, param2, ...)
param
is optional, which can be passed to the function.
The return value of setInterval()
is the Id of the timer. We can use clearInterval(Id)
to cancel the timer.
H3setTimeout()
The setTimeout()
method calls a function after a number of milliseconds.
Syntax: setTimeout(function, milliseconds, [param1, param2, ...])
param
is optional, which can be passed to the function.
The return value of setTimeout()
is also the Id of the timer.
H3scrollTo()
The scrollTo()
method scrolls the document to specified coordinates(坐标).
Syntax: scrollTo(x-coord, y-coord)
x-coord
是文档中的横轴坐标。y-coord
是文档中的纵轴坐标。
Syntax: scrollTo(options)
options
是一个包含三个属性的对象:
top
等同于y-coord
left
等同于x-coord
behavior
类型 String,表示滚动行为,支持参数 smooth(平滑滚动),instant(瞬间滚动),默认值 auto
例如:
H1Expressions & Operators
H2in & delete
H1Web APIs
H2FormData
Note:
formData
is a type of Map.
Methods:
FormData.get()
FormData.forEach()