学习内容
- 类数组/伪数组
- Array.from()
- Array.of()
- copyWithin()
- fill()
- includes()
类数组/伪数组
下面这几行代码的返回值就是伪数组。伪数组有索引,且长度是非负的整数,即长度length属性,但是没有数组的方法,比如push。
let divs = document.getElementsByTagName('input')
console.log(divs)
let divs2 = document.getElementsByClassName('hh')
console.log(divs2)
let divs3 = document.querySelectorAll('.hh')
console.log(divs3)
console.log(divs3 instanceof Array)
divs3.push(123)
---------------------------------
HTMLCollection []
HTMLCollection []
NodeList []
false // nodelist也不是数组
TypeError: divs3.push is not a function
ES5中Array有一个slice方法,可以把伪数组转为真正的数组:
let divs3 = document.querySelectorAll('.hh')
console.log(divs3)
let arr = Array.prototype.slice.call(divs3)
console.log(arr)
---------------------------
[]
length: 0
[[Prototype]]: Array(0)
下面这个arguments也是一个伪数组:
function foo() {
console.log(arguments)
console.log(arguments instanceof Array)
}
foo(1,'test',true)
---------------------------------------------------------------------
Arguments(3) [1, 'test', true, callee: ƒ, Symbol(Symbol.iterator): ƒ]
0: 1
1: "test"
2: true
callee: ƒ foo()
length: 3
Symbol(Symbol.iterator): ƒ values()
[[Prototype]]: Object
false
Array.from()
ES6当中也有一个方法Array.from来把伪数组转为真正的数组,而且很简便:
let arrayLike = {
0:'es6',
1:'es7',
2:'es8',
length:3
}
let arr = Array.from(arrayLike)
console.log(arr)
console.log(arr[1])
-----------------------------
(3) ['es6', 'es7', 'es8']
es7
Array.of()
对比如下程序:
let arr1 = new Array(1,2)
console.log(arr1)
let arr2 = new Array(3)
console.log(arr2)
--------------------------------------------------------------------
(2) [1, 2]
(3) [empty × 3] // 这里的3变成了数组的个数,而不是数组里只有一个元素3
这时就可以通过Array.of来实现初始化数组的功能,只初始化一个参数也是OK的:
let arr1 = Array.of(1,2)
console.log(arr1)
let arr2 = Array.of(3)
console.log(arr2)
-------------------------------
(2) [1, 2]
[3]
比如有一个需求是将收到的各种各样的数据拼成一个数组,就可以使用Array.of(),如:
let arr = Array.of(1,'2',true,[1,2,3],{
name:'sure'
})
console.log(arr)
----------------------------------
(5) [1, '2', true, Array(3), {…}]
0: 1
1: "2"
2: true
3: (3) [1, 2, 3]
4: {name: 'sure'}
length: 5
[[Prototype]]: Array(0)
copyWithin()
可以替换数组里的元素:
let arr = [1,2,3,4,5]
// 第一个参数必填表示从下标位置开始去替换数据,
// 第二个参数可选表示从下标位置开始读取元素,
// 第三个参数可选表示到下标位置停止读取元素,
// 第三个参数不选表示读取到末尾
console.log(arr.copyWithin(1 ,3))
-----------------------------
(5) [1, 4, 5, 4, 5]
fill()
应用场景一:
let arr = new Array(3).fill(7)
console.log(arr)
----------------------------
(3) [7, 7, 7]
应用场景二:
let arr = [1,2,3,4,5]
// 用test从下标1开始填充一直到3,但不包含下标3
arr.fill('test', 1, 3)
console.log(arr)
------------------------------
(5) [1, 'test', 'test', 4, 5]
let arr = [1,2,3,4,5]
arr.fill(0) // 全部替换
console.log(arr)
----------------------------
(5) [0, 0, 0, 0, 0]
includes()
indexOf返回下标索引,对于NaN无法返回,includes返回布尔值,但是可以找到NaN:
let arr = [1, 2, 3, NaN]
console.log(arr.indexOf(NaN))
console.log(NaN == NaN)
console.log(arr.includes(NaN))
-----------------
-1
false
true