ES系列 | 数组的扩展

234 阅读2分钟

「这是我参与2022首次更文挑战的第7天,活动详情查看:2022首次更文挑战」。

ES系列文章

ES6数组的扩展

  • 类数组/伪数组
  • Array.from()
  • Array.of()
  • copyWithin()
  • fill()
  • includes()

类数组/伪数组(不是真正意义上的数组)

伪数组具备两个特征:

  1. 按索引方式储存数据
  2. 有length属性
//HTMLCollection是伪数组
let divs=document.getElementsByTagName('div')
console.log(divs)//HTMLCollection

let divs2=document.getElementsByClassName('xxx')
console.log(divs2)//HTMLCollection
//NodeList是伪数组
//querySelectorAll() 方法返回文档中匹配指定 CSS 选择器的所有元素,返回 NodeList 对象。
let divs3=document.querySelectorAll('.xxx')
console.log(divs3)//NodeList
console.log(divs3 instanceof Array)//false

使用instanceof来检测某个对象是否是数组的实例,返回true则是数组,返回false则不是数组

//arguments是伪数组
function foo(){
    console.log(arguments)//1 mooc true
    console.log(arguments instanceof Array)//false 
}
foo(1,'mooc',true)

伪数组不具有数组的方法

  • arr.push()方法是向数组尾部添加项
  • push()不是方法,push()是Array数组下面的

Array.from()将伪数组转换成数组

ES5:做法

let arr = Array.prototype.slice.call(divs3)
console.log(arr)
arr.push(123)
console.log(arr)

ES5:做法

let arrayList={
    0:"es6",
    1:"es7",
    2:"es8",
    length:3
}
let arr = Array.from(arrayLike)
arr.push("es9")
console.log(arr)

Array.of()构造数组

构造数组的两种方式:

  1. Array 构造函数
//new Array()
let arr=new Array(1,2)
console.log(arr)
//[1,2]

let arr2=new Array(3)
console.log(arr2)
//[empty*3]
  1. Array.of()构造数组
//Array.of()
let arr=Array.of(1,2)
console.log(arr)
//[1,2]

let arr2=Array.of(3)
console.log(arr2)
//[3]

let arr=Array.of(1,true,'hello',[1,2,3],{
    name:'wdl'
})
console.log(arr)//[1, true, "hello", Array(3), {name:'wdl'}]

Array.prototype.copyWithin()数组浅拷贝

Array.prototype.copyWithin(target,start,end) 浅复制数组的一部分到同一数组中的另一个位置,并返回它,改变原数组但不改变原数组的长度

参数描述
target复制序列到该位置
start开始复制元素的起始位置,如果 start 被忽略,copyWithin 将会从0开始复制。
end开始复制元素的结束位置。copyWithin 将会拷贝到该位置,但不包括 end 这个位置的元素。
//copyWithin()
let arr=[1,2,3,4,5]
console.log(arr.copyWithin(1,3))//[1,4,5,4,5]
console.log(arr)//[1,4,5,4,5]

Array.prototype.fill()数组填充

Array.prototype.fill(value,start,end) 改变原数组,返回修改过的数组

参数描述
value用来填充数组元素的值。
start起始索引,默认值为0。
end终止索引,默认值为 this.length。
let arr1=new Array(3).fill(7)
console.log(arr1)//[7,7,7]

let arr2=[1,2,3,4,5]
arr2.fill('hello',1,3)
console.log(arr2)//[1, "hello", "hello", 4, 5]

Array.prototype.includes()判断一个数组是否包含目标值

与indexOf()区别:

  • indexOf返回数组下标,includes()返回布尔值
  • indexOf无法检验NaN,includes()可以
let arr=[1,2,3,NaN]
console.log(arr.indexOf(NaN))//-1
console.log(arr.includes(NaN))//true
console.log(NaN==NaN)//false

一个前端小白,若文章有错误内容,欢迎大佬指点讨论!