es6 数组的新增方法欢迎使用CSDN-markdown编辑器

    技术2025-10-25  10

    数组的扩展

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

    类数组 / 伪数组:

    什么是类数组或者伪数组呢?? >> **指的就是不是真正意义上的数组 **如:

    let div1 = document.getElementsByTagName('div') console.log(div1) // HTMLCollection [] let div2 = document.getElementsByClassName('div') console.log(div2) // HTMLCollection [] let div3 = document.querySelectorAll('.xx') console.log(div3) // NodeList []

    从以上代码输出信息可知 具有数组的标识 [] 和 length 但是想这些数组中使用 push() 方法就会报错 从这步可以检测出 这些数组不是真正意义上的数组 不具有数组的方法 但是具有数组的 length 属性 故称之为 伪数组 / 类数组

    检测数组的方法:

    console.log(div2 instanceof Array) // true 是数组 false 就不是数组

    问题: 如何将伪数组转换为真正意义上的数组呢??

    // ES5 做法 let arr = Arrray.prototype.slice.call(div3) console.log(arr) // [] arr.push(123) console.log(arr) [123]

    函数参数的 argument 参数也是一个伪数组

    ES6 中有没有直接转化为数组的方法 Array.from()

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

    使用数组的构造函数的一些问题

    let arr = new Array(1, 2) // 当参数为两个以上时 这里的参数就是 数组的每项值 console.log(arr) // [1, 2] let arr = new Array(3) // 当参数为 1 个时 代表初始化的数组的长度 console.log(arr.length) // 3

    如何优雅的处理以上的问题呢? Array.of() 方法即可解决

    let arr = Array.of(3) console.log(arr) // [3] let arr = Array.of(3, 5, 7) console.log(arr) // [3, 5, 7]

    Array.of() 就是为了处理数组构造器存在的一些问题而设定 使用这个方法即使值传入一个参数 也会是数组的项值 而不是数组的长度值

    用法:

    let arr = Array.of(1, 'name', true, [1, 'xiaojian', false, {age: 12}], {age: 23}) console.log(arr)

    通过以上的输出结论可知: 我们可以将各种各样的数据通过 Array.of 方式拼成一个数组

    数组值替换: Array.copyWithin()

    let arr = [1, 2, 3, 4, 5] console.log(arr.copyWithin(arr)) // [1, 4, 5, 4, 5]

    copyWithin() 支持3个参数:

    target: 复制到指定目标索引位置

    start: 元素复制的起始位置

    end: 停止复制的索引位置(默认为 array.length) 如果为负值,表示倒数

    数组填充: Array.fill()

    let arr = [1, 2, 3, 4, 5] arr.fill('xiaojian', 1, 3) console.log(arr) // [1, 'xiaojian', 'xiaojian', 4, 5 ] // 如果只传入一个参数 arr.fill(0) console.log(arr) // 0,0,0,0,0

    fill() 支持3个参数:

    value: 填充的值 [必传]

    start: 开始填充位置 [可选]

    end: 停止填充位置 [可选] 默认是数组的长度

    是否包含: includes()

    在 es5 之前为了检测某一个项是不是在数组中存在 通常通过 indexOf() 方法配合

    indexOf() 方法可以获得数组元素在数组中的索引 如果存在就会返回索引值 不存在就会返回 -1

    然而有以下情况:

    let arr = [1, 2, 3, NaN] console.log(arr.indexOf(NaN)) // -1 console.log(NaN == NaN) // false 在js 中 NaN 是不等于 NaN 的 所以在数组中通过 indexOf() 方法得到的就是 -1

    以上情况可以通过 includes() 方法即可处理

    let arr = [1, 2, 3, NaN] arr.includes(NaN) // true
    Processed: 0.013, SQL: 9