ES6 数组的扩展

一、数组的 扩展运算符 ...

1. 语法

  • 它好比 rest 参数的逆运算,将一个数组转为用逗号分隔的参数序列

  • 语法:

    • [...真数组][...伪数组]

2. ...array 等同于 apply() 方法

// 求 数组中最大值 [14, 3, 77] 

// ES5 的写法
Math.max.apply(null, [14, 3, 77])

// ES6 的写法
Math.max(...[14, 3, 77])

3. [...array] 可合并数组

// ES6 合并数组

var arr1 = [1, 2];
var arr2 = [3, 4];
var result = [...arr1, ...arr2];

console.log(result);        // [1, 2, 3, 4]
// ES5 合并数组

var arr1 = [1, 2];
var arr2 = [3, 4];
var result = arr1.concat(arr2);

console.log(result);        // [1, 2, 3, 4]

4. [...array] 可复制数组(数组项为对象时,是浅拷贝)

  • 可拷贝数组(在内存中,开辟一块新的空间),但数组项为对象时,只是拷贝对象的引用
const a = {
    name: 'zhang',
    info: {
        age: 18
    }
};
const aClone = [...a];

a.name = 'xin';
a.info.age = 20;
console.log(aClone);    // aClone.name 值为 'zhang';aClone.info.age 值为20

5. [...array] 可将伪数组(部署了 Iterator 接口) 变 真数组

  • 前提: 伪数组 必须是部署了 Iterator 接口的对象
// 将 ES5 中 函数内部的 arguments 是伪数组

function fn (a, b, c) {
    // ES6 写法
    [...arguments].forEach((item) => {
        console.log(item);
    });
    
    // ES5 写法
    [].slice.call(arguments).forEach((item) => {
        console.log(item);
    });
}

fn(1, 2, 3);   // 1 2 3   1 2 3

6. [...array] 可将字符串 变 真数组

console.log([...'hello']);          // [ "h", "e", "l", "l", "o" ]

二、伪数组转真数组 Array.from()

1. 语法 Array.from(arr, function, this)

  • 参数1: arrayLike 想要转换成数组的伪数组对象 或 可迭代对象

  • 参数2: (可选)回调函数(参数为转换后的数组),集体操作 数组中每一项(类似 map 方法)

  • 参数3: (可选)绑定回调函数中 this 指向

  • 返回值: 真数组

Array.from(arrayLike, x => x * x);
// 等同于
Array.from(arrayLike).map(x => x * x);

Array.from([1, 2, 3], (x) => x * x)
// [1, 4, 9]

2. 将 类似于数组的对象 转成 真数组

  • 类似于数组的对象: 必须有 .length 属性
var obj = {
    a: 'zhang', 
    '0': 222, 
    '3': 111, 
    length: 4}

var result = Array.from(obj);
console.log(result);             // 222, undefined, undefined, 111]

result.length = 2;
console.log(result);            // [222, undefined]
console.log(Array.from({ length: 3 }));     // [ undefined, undefined, undefined ]

3. 将 部署了 Iterator 接口 的对象 转成 真数组

4. 将 字符串 转成 真数组

  • 返回值: 字符串的长度
console.log(Array.from('hello'));     // ['h', 'e', 'l', 'l', 'o']

三、创建数组 Array.of();弥补了 ES5中 Array() 创建数组的 不足

  • 语法
    • 参数: 可接受多个

    • 返回值: 由参数构成的新数组

console.log(Array.of());                // []

console.log(Array.of(undefined));       // [undefined]

console.log(Array.of(3));               // [3]

console.log(Array.of(1, 2));            // [1, 2]
  • Array.of() 弥补了 new Array() 的不足

    • ES5中 new Array() 不足:

    • ES6中 Array.of() 创建数组

// ES5 中创建数组
console.log(new Array(1, 2, 4));            // [1, 2, 4]

console.log(new Array(3));                  // [,,,]
// ES6 中创建数组
console.log(Array.of(1, 2, 4));            // [1, 2, 4]

console.log(Array.of(3));                  // [3]

四、 查找 是否包含数组项 includes(item, start, end) ---> 弥补了ES5 查找NaN的不足

  • 作用: 查找是否包含 数组项

  • 语法: myArray.includes(item, start, end)

    • 参数 item:(必需)检测项

    • 参数 start: (可选)从该位置开始填充数据,默认为 0; 不支持负数(填充不生效)

    • 参数 start: (可选)到该位置前停止填充数据,默认等于数组长度(即截取到最后一位)【不包含 该索引项】;不支持负数(填充不生效)

    • 返回值:原数组 并 作为返回值返回

  • 弥补了ES5 查找NaN的不足

// ES6 实现

console.log([NaN].includes(NaN));       // true

五、查找数组项 find() 、findIndex()

1. find() 找出 第一个 符合条件的 数组项的 索引,并返回;找不到返回 undefined

  • 语法:
    • 参数1:回调函数(回调函数中 return 寻找条件;直到找出第一个返回值为true的成员 / 成员的索引);回调函数接受三个参数 valueindexarrarr 是原数组)

    • 参数2:绑定回调函数中 this 指向

[1, 4, -5, 10].find((n) => n < 0)
// -5

2. findIndex() 找出 第一个 符合条件的 数组项,并返回;找不到返回 -1

  • 语法:
    • 参数1:回调函数(回调函数中 return 寻找条件;直到找出第一个返回值为true的成员 / 成员的索引);回调函数接受三个参数 valueindexarrarr 是原数组)

    • 参数2:绑定回调函数中 this 指向

[1, 5, 10, 15].findIndex(function(value, index, arr) {
    return value > 9;
}) // 2

3. 弥补了 ES5中 indexOf() 方法,不能识别 NaN 的不足

  • 结合 Object.is() 方法,可以识别出 NaN
console.log([NaN].indexOf(NaN));                            // -1

console.log([NaN].findIndex(y => Object.is(NaN, y)));       // 0

六、 移动 并 覆盖数组项 myArray.copyWithin(target, start, end)

  • 在当前数组内部,将指定位置的成员复制到其他位置(会覆盖原有成员),然后返回当前数组(原数组改变)

  • 语法:

    • 参数 start:(必需)从该位置开始替换数据;如果为负值,表示倒数

    • 参数 start: (可选)从该位置开始读取数据,默认为 0;如果为负值,表示倒数

    • 参数 start: (可选)到该位置前停止读取数据,默认等于数组长度(即截取到最后一位)【不包含 该索引项】;如果为负值,表示倒数

    • 返回值:原数组 并 作为返回值返回

var arr1 = [1, 2, 3, 4, 5];
var arr2 = arr1.copyWithin(0, 3);

console.log(arr2);      // [4, 5, 3, 4, 5]
console.log(arr1);      // [4, 5, 3, 4, 5]
var arr1 = [1, 2, 3, 4, 5];
var arr2 = arr1.copyWithin(0, -2, -1);

console.log(arr2);      // [4, 2, 3, 4, 5]
console.log(arr1);      // [4, 2, 3, 4, 5]

七、 填充数组项 myArray.fill(item, start, end)

  • 作用: 填充数组

  • 语法:

    • 参数 item:(必需)填充项

    • 参数 start: (可选)从该位置开始查找数据,默认为 0; 如果为负值,表示倒数

    • 参数 start: (可选)到该位置前停止查找数据,默认等于数组长度(即截取到最后一位)【包含:该索引项】;如果为负值,表示倒数

    • 返回值:布尔值

console.log([1, 2, 3, 4].includes(2));              // true

console.log([1, 2, 3, 4].includes(2, 5));           // false

console.log([1, 2, 3, 4].includes(4, 2, 3));        // true 查找范围包含了 结束索引

八、 遍历数组:entries()keys()values()

  • 以上三种方法:不传参;返回值是数组

  • 语法

    • myArray.entries() :返回 键值对 构成的 二维数组

    • myArray.keys() :返回 键名 构成的 一维数组

    • myArray.values() :返回 值 构成的 一维数组

  • 应用: 返回值一个遍历器(迭代器)对象

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

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

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

九、 数组的空位 规范化

  • ES6规范:
    • ES6方法中,不会忽略空位,将空位明确转为 undefined

    • for...of循环也会遍历空位

Array.from(['a',,'b']);     // [ "a", undefined, "b" ]

[...['a',,'b']];            // [ "a", undefined, "b" ]

[...[,'a'].entries()]       // [[0,undefined], [1,"a"]]
  • ES5语法:处理很不统一:

    • forEach(), filter(), reduce(), every() 和some()都会跳过空位

    • map()会跳过空位,但会保留这个值

    • join()和toString()会将空位视为undefined,而undefined和null会被处理成空字符串

原文地址:https://www.cnblogs.com/zxvictory/p/8421305.html