Array
constructor
ts
new Array()
new Array(length)
new Array(element0, element1, ..., elementN)无参数:创建空数组
tsconst arr = new Array() console.log(arr) // []传入一个数字参数:创建指定长度的稀疏数组,
tsconst arr = new Array(3) console.log(arr) // [ 空属性*3 ] console.log(arr.length) // 3传入多个参数:创建并初始化数组
tsconst arr = new Array(1, 2, 3) console.log(arr) // [1, 2, 3]
Array.of
根据一组参数创建一个新的数组实例
ts
Array.of(element0[, element1[, ...[, elementN]]])ts
Array.of(1, 2, 3)
// → [1, 2, 3]
Array.of(7)
// → [7]
Array.of()
// → []与 Array() 的区别
Array() 在参数为一个数字时会创建“空洞数组”,而 Array.of() 总是把参数当作元素值。
ts
Array(7) // 创建一个长度为7的空数组(稀疏数组)
Array.of(7) // 创建一个包含单个元素 7 的数组Array.isArray
判断一个值是否为数组
ts
Array.isArray(value)Array.from
用于从类数组对象或可迭代对象创建一个新的数组实例
ts
Array.from(arrayLike)
Array.from(arrayLike, mapFn)
Array.from(arrayLike, mapFn, thisArg)Params
想要转换成数组的类数组或可迭代对象。
mapFn可选调用数组每个元素的函数。如果提供,每个将要添加到数组中的值首先会传递给该函数,然后将
mapFn的返回值增加到数组中。使用以下参数调用该函数:
element数组当前正在处理的元素。
index数组当前正在处理的元素的索引。thisArg可选可选执行
mapFn时用作this的值。
Use
把类数组对象转成真正的数组
tsArray.from('abc') // ['a', 'b', 'c'] Array.from(new Set([1, 2, 3])) // [1, 2, 3] const divs = document.querySelectorAll('div') const arr = Array.from(divs) arr.forEach(div => console.log(div))Array.from(arrayLike, mapFn)tsArray.from([1, 2, 3], x => x * 2) // → [2, 4, 6]创建非稀疏数组
ts
const arr=Array.from({ length: 3 })
console.log(arr)//[undefined,undefined,undefined]ArrayCallbackFn
ts
type ArrayCallback<R=void> = <T>(element: T, index: number, array: T[]) => R| 参数 | 含义 | 类型 |
|---|---|---|
T | 数组元素类型,T 由上下文推断 | 泛型 |
R | 回调返回值类型(默认 void) | 泛型,可指定 |
该函数被调用时将传入以下参数:
element数组中当前正在处理的元素。index正在处理的元素在数组中的索引。array调用实例方法的数组本身。
