ES6-Array

Array

from()

  • 必须是arrayLike对象,没有length属性时,默认length为0
var arrObj = {
    0: '0',
    1: '1',
    2: '2'
}
var arr = Array.from(arrObj); // []
  • 根据key生成响应的数组index。其它以undefined填充
var arrObj = {
    1: '0',
    2: '1',
    3: '2',
    length: 5
}
var arr = Array.from(arrObj); // [undefined, '0', '1', '2', undefined]
  • 传入第二个参数用于对每一个元素进行处理
var arrObj = {
    1: '0',
    2: '1',
    3: '2',
    length: 5
}
var arr = Array.from(arrObj, (item) => {
    return item || 'hahah';
}); // ['hahah', '0', '1', '2', 'hahah']
  • 传入第三个参数,用于改变this指向

of()

  • 将一组值转换成数组
Array.of(3, 4, 5); // [3, 4, 5]

copyWithin()

// 将3号位复制到0号位
[1, 2, 3, 4, 5].copyWithin(0, 3, 4)
// [4, 2, 3, 4, 5]

// -2相当于3号位,-1相当于4号位
[1, 2, 3, 4, 5].copyWithin(0, -2, -1)
// [4, 2, 3, 4, 5]

// 将3号位复制到0号位
[].copyWithin.call({length: 5, 3: 1}, 0, 3)
// {0: 1, 3: 1, length: 5}

// 将2号位到数组结束,复制到0号位
var i32a = new Int32Array([1, 2, 3, 4, 5]);
i32a.copyWithin(0, 2);
// Int32Array [3, 4, 5, 4, 5]

// 对于没有部署TypedArray的copyWithin方法的平台
// 需要采用下面的写法
[].copyWithin.call(new Int32Array([1, 2, 3, 4, 5]), 0, 3, 4);
// Int32Array [4, 2, 3, 4, 5]

find()

  • 找出第一个符合条件的数组成员
[0, 1, 3, 4].find((item) => item < 2) // 0
  • 回调的三个参数
[0, 1, 3, 4].find((item, index, arr) => {
    return item > 1
    console.log(item);
    console.log(index);
    console.log(arr);
})

findIndex()

  • indexOf无法判断NAN
  • indexOf无法判断数组中的对象
  • 如果没有匹配的值,返回-1
[0, 1, 3, 4].findIndex((item, index, arr) => {
    return item > 1;
}) // 2

arr.fill(item, start, end)

['a', 'b', 'c'].fill(7)
// [7, 7, 7]

new Array(3).fill(7)
// [7, 7, 7]

['a', 'b', 'c'].fill(7, 1, 2)
// ['a', 7, 'c']

arr.entries()

for (let [index, elem] of ['a', 'b'].entries()) {
  console.log(index, elem);
}
// 0 "a"
// 1 "b"

arr.keys()

for (let index of ['a', 'b'].keys()) {
  console.log(index);
}
// 0
// 1

arr.values()

for (let elem of ['a', 'b'].values()) {
  console.log(elem);
}
// 'a'
// 'b'

空位处理

  • 所有ES6方法都明确将数组中的空位转换成undefined
Array.from(['a',,'b'])
// [ "a", undefined, "b" ]

[...['a',,'b']]
// [ "a", undefined, "b" ]
原文地址:https://www.cnblogs.com/ddfe/p/5609694.html