你的浏览器不支持canvas

Enjoy life!

ES6 - 数组的扩展

Date: Author: JM

本文章采用 知识共享署名-非商业性使用-禁止演绎 4.0 国际许可协议 进行许可。

其他链接:

以下内容全部源于: http://es6.ruanyifeng.com/#docs/array

1、扩展运算符 (spread)

1.1 含义

  • 扩展运算符是三个点(…)。它好比 rest 参数的逆运算,将一个数组转为用逗号分隔的参数序列。
console.log(1, ...[2, 3, 4], 5)  // 1 2 3 4 5
  • 该运算符主要用于函数调用。
function f(v, w, x, y, z) { }
var args = [0, 1];
f(-1, ...args, 2, ...[3]);
  • 扩展运算符后面还可以放置表达式。
const arr = [
  ...(x > 0 ? ['a'] : []),
  'b',
];
  • 如果扩展运算符后面是一个空数组,则不产生任何效果。
[...[], 1]  // [1]

1.2、替代数组的 apply 方法

  • 由于扩展运算符可以展开数组,所以不再需要apply方法,将数组转为函数的参数了。
function f(x, y, z) {
  // ...
}
var args = [0, 1, 2];

// ES5 的写法
f.apply(null, args);

// ES6的写法
f(...args);
  • 下面是扩展运算符取代apply方法的一个实际的例子,应用Math.max方法,简化求出一个数组最大元素的写法。
// ES5 的写法
Math.max.apply(null, [14, 3, 77])

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

// 等同于
Math.max(14, 3, 77);

1.3 扩展运算符的应用

  • 合并数组【点击打开demo
    let arr1 = ['a', 'b'];
    let arr2 = [1, 2];
    let arr3 = [5, 'c'];

    // es5
    console.log(arr1.concat(arr2, arr3) ) // ["a", "b", 1, 2, 5, "c"]

    // es6
    console.log([...arr1, ...arr2, ...arr3]) // ["a", "b", 1, 2, 5, "c"]

  • 与解构赋值结合【点击打开demo
  • Rest element must be last element ===》 扩展运算符只能放在参数的最后一位
    const [first, ...rest1] = [1, 2, 3, 4, 5];
    console.log(first, rest1); // 1 [2, 3, 4, 5]

    const [second, ...rest2] = [];
    console.log(second, rest2); // undefined []

    const [third, ...rest3] = ['foo'];
    console.log(third, rest3); // foo []

    // 报错: Rest element must be last element
    // const [...rest4, last] = [1, 2, 3, 4, 5];

  • 字符串 【点击打开demo
    • 扩展运算符还可以将字符串转为真正的数组。
    • 还能够正确识别32位的 Unicode 字符。
      • JavaScript 会将32位 Unicode 字符,识别为2个字符,采用扩展运算符就没有这个问题。
    // 例1
    console.log([...'hello']); // ["h", "e", "l", "l", "o"]

    // 例2
    function getLength (str) {
      return [...str].length;
    }

    let str = 'x\uD83D\uDE80y'
    console.log(getLength(str)) // 3
    console.log(str.length); // 4

    // 如果不用扩展运算符,字符串的reverse操作就不正确。
    console.log(str.split('').reverse().join()) // y,�,�,x
    console.log([...str].reverse().join()); // y,🚀,x

  • 实现了 Iterator 接口的对象 【点击打开demo
    • 任何 Iterator 接口的对象,都可以用扩展运算符转为真正的数组。
    • querySelectorAll方法返回的是一个nodeList对象。它不是数组,而是一个类似数组的对象。这时,扩展运算符可以将其转为真正的数组,原因就在于NodeList对象实现了 Iterator
    • 对于那些没有部署 Iterator 接口的类似数组的对象,扩展运算符就无法将其转为真正的数组。
    // 例1:将类数组转化为真正的数组
    let nodeLsit = document.querySelectorAll('div');
    console.log(nodeLsit); // 还是 NodeList
    console.log([...nodeLsit]); // 变成 Array

    // 例2:没有部署 Iterator 接口,扩展运算符报错
    // 使用`Array.from`方法将`arrayLike`转为真正的数组
    let arrayLike = {
      '0': 'a',
      '1': 'b',
      '2': 'c',
      length: 3
    };
    // 报错:TypeError: arrayLike is not iterable
    // console.log([...arrayLike])
    console.log(Array.from(arrayLike)); // ["a", "b", "c"]

  • MapSet 结构,Generator 函数 【点击打开demo
    • 扩展运算符内部调用的是数据结构的 Iterator 接口,因此只要具有 Iterator 接口的对象,都可以使用扩展运算符,比如 Map 结构。
    • Generator 函数运行后,返回一个遍历器对象,因此也可以使用扩展运算符。
    // 例1:Map
    let map = new Map(
      [
        [1, 'one'],
        [2, 'two'],
        [3, 'three'],
      ]
    )
    console.log([...map.keys()]) // [1, 2, 3]

    // 例2 Generator - 执行后返回的是一个遍历器对象
    // 对这个遍历器对象执行扩展运算符,就会将内部遍历得到的值,转为一个数组
    let go = function* () {
      yield 1;
      yield 2;
      yield 3;
    }
    console.log(...go()); // 1 2 3

2、Array.from()

2.1 Array.from()的基本用法(只传一个参数)

  • Array.from方法用于将两类对象转为真正的数组:类似数组的对象(array-like object)和可遍历(iterable)的对象(包括ES6新增的数据结构SetMap)。
  • 实际应用中,常见的类似数组的对象是DOM 操作返回的 NodeList 集合,以及函数内部的arguments对象,Array.from都可以将它们转为真正的数组。
  • 【点击打开demo
    // 例1:
    let arrayLike = {
      '0': 'a',
      '1': 'b',
      '2': 'c',
      length: 3
    };
    // es5
    console.log([].slice.call(arrayLike)) // ["a", "b", "c"]
    // es6
    console.log(Array.from(arrayLike)) // ["a", "b", "c"]

    // 如果参数是一个真正的数组,Array.from会返回一个一模一样的新数组
    console.log(Array.from([1, 2, 3])); // [1, 2, 3]
  • 扩展运算符(…)也可以将某些数据结构转为数组。
    • 扩展运算符背后调用的是遍历器接口(Symbol.iterator),如果一个对象没有部署这个接口,就无法转换。
    • Array.from 方法还支持类似数组的对象。所谓类似数组的对象,本质特征只有一点,即必须有length属性
    • 因此,任何有 length 属性的对象,都可以通过 Array.from 方法转为数组,而此时扩展运算符就无法转换。
// arguments对象
function foo() {
  var args = [...arguments];
}

// NodeList对象
[...document.querySelectorAll('div')]

// 有本质特征的类数组
Array.from({ length: 3 });// [ undefined, undefined, undefined ]

2.2 Array.from()的进阶(传第二个参数)

  • 第二个参数,作用类似于数组的map方法,用来对每个元素进行处理,将处理后的值放入返回的数组。
  • 【点击打开demo
    // 例1:
    Array.from([1, 2, 3], (item) => {
      console.log(item);
      // 1
      // 2
      // 3
    })

    // 例2:将数组中布尔值为false的成员转为0。
    console.log(Array.from([1, , 2, , 3], (n) => n || 0))  // [1, 0, 2, 0, 3]

    // 例3:返回各种数据的类型。
    function typesOf () {
      return Array.from(arguments, value => typeof value)
    }
    console.log( typesOf(null, [], NaN)) // ['object', 'object', 'number']

    // 例4:Array.from的第一个参数指定了第二个参数运行的次数。
    console.log(Array.from({ length: 2 }, () => 'jack')) // ['jack', 'jack']

2.2 Array.from()的进阶(传第三个参数)

  • 如果map函数里面用到了this关键字,还可以传入 Array.from 的第三个参数,用来绑定 this
  • Array.from() 可以将各种值转为真正的数组,并且还提供map功能。这实际上意味着,只要有一个原始的数据结构,你就可以先对它的值进行处理,然后转成规范的数组结构,进而就可以使用数量众多的数组方法

2.3 Array.from()应用

  • 将字符串转为数组,然后返回字符串的长度。因为它能正确处理各种 Unicode 字符,可以避免 JavaScript 将大于 \uFFFFUnicode 字符,算作两个字符的 bug
    function countSymbols(string) {
    return Array.from(string).length;
    }
    

3、Array.of()

  • Array():只有当参数个数不少于2个时,Array()才会返回由参数组成的新数组。参数个数只有一个时,实际上是指定数组的长度。
  • Array.of方法用于将一组值,转换为数组。
    • 主要目的:弥补数组构造函数Array()的不足。因为参数个数的不同,会导致Array()的行为有差异。
    • Array.of基本上可以用来替代Array()new Array(),并且不存在由于参数不同而导致的重载。它的行为非常统一。
    • Array.of总是返回参数值组成的数组。如果没有参数,就返回一个空数组。
  • 【点击打开demo
    // 例1:Array()
    console.log(Array()); // []
    console.log(Array(3)); // [, , ,]
    console.log(Array(3, 11, 8)); // [3, 11, 8]

    // 例2:Array.of()
    console.log(Array.of()); // []
    console.log(Array.of(3)); // [3]
    console.log(Array.of(3, 11, 8)); // [3, 11, 8]


  • Array.of方法可以用下面的代码模拟实现。
function ArrayOf(){
  return [].slice.call(arguments);
}

4、数组实例的 copyWithin(target, start, end)

  • 数组实例的 copyWithin方法,在当前数组内部,将指定位置的成员复制到其他位置(会覆盖原有成员),然后返回当前数组。即:使用这个方法,会修改当前数组
  • 接受三个参数
    • target(必需):从该位置开始替换数据。
    • start(可选):从该位置开始读取数据,默认为0。如果为负值,表示倒数。
    • end(可选):到该位置前停止读取数据,默认等于数组长度。如果为负值,表示倒数
  • 【点击打开demo
    // 将3号位复制到0号位
    console.log([1, 2, 3, 4, 5].copyWithin(0, 3, 4))  // [4, 2, 3, 4, 5]

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

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

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

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

5、数组实例的 find() 和 findIndex()

5.1 find()

  • find()方法,用于找出第一个符合条件的数组成员。
    • 它的参数是一个回调函数,所有数组成员依次执行该回调函数,直到找出 第一个返回值为true的成员,然后返回该成员。如果没有符合条件的成员,则返回 undefined
      • find方法的回调函数可以接受三个参数,依次为 当前的值当前的位置原数组
  • 【点击打开demo
    let arr = [1, 5, 10, 14];
    const result = arr.find((value, index, arr) => {
      return value > 9;
    })
    console.log(result); // 10

5.2 findIndex()

  • find 方法非常类似,返回第一个符合条件的数组成员的位置,如果所有成员都不符合条件,则返回-1。
  • 【点击打开demo
    let arr = [1, 5, 10, 14];
    const result = arr.findIndex((value, index, arr) => {
      return value > 9;
    })
    console.log(result); // 2

5.3 两者共同点

  1. 这两个方法都可以接受第二个参数,用来绑定回调函数的this对象。
  2. 两个方法都可以发现NaN,弥补了数组的IndexOf方法的不足。
    • indexOf方法无法识别数组的 NaN 成员,但是findIndex方法可以借助Object.is 方法做到。
  • 【点击打开demo
    console.log([NaN].indexOf(NaN)); // -1

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

6、数组实例的fill()

  • fill方法使用给定值,填充一个数组。
  • fill方法用于空数组的初始化非常方便。数组中已有的元素,会被全部抹去。
  • fill方法还可以接受第二个和第三个参数,用于指定填充的起始位置和结束位置。
  • 【点击打开demo
    let result1 = ['a', 'b', 'c'].fill(7);
    console.log(result1); // [7, 7, 7]

    let result2 = new Array(4).fill(3);
    console.log(result2); // [3, 3, 3, 3]

    // 从1号位开始,向原数组填充7,到2号位之前结束
    let result3 = ['a', 'b', 'c'].fill(7, 1, 2);
    console.log(result3); // ["a", 7, "c"]

8、 数组实例的 entries(),keys() 和 values()

  • entries()keys()values()——用于遍历数组。它们都返回一个遍历器对象,可以用 for...of 循环进行遍历,唯一的区别:
    • keys()是对键名的遍历。
    • values()是对键值的遍历。【兼容性问题,暂时大多数浏览器不支持,都会报错】
    • entries()是对键值对的遍历。
  • 【点击打开demo
    let arr = ['a', 'b', 'c'];

    // keys()
    for (let index of arr.keys()) {
      console.log(`index:${index}`);
      // index:0
      // index:1
      // index:2
    }

    // values() -- 大多数浏览器暂时不兼容 - 报错
//    for (let ele of arr.values()) {
//      console.log(`value:${ele}`);
//    }

    for (let [index, ele] of arr.entries()) {
      console.log(`index:${index}, value:${ele}`)
      // index:0, value:a
      // index:1, value:d
      // index:2, value:c
    }

// 如果不使用for...of循环,可以手动调用遍历器对象的next方法,进行遍历。
let entries = arr.entries();
console.log(entries.next().value); // [0, 'a']
console.log(entries.next().value); // [1, 'b']
console.log(entries.next().value); // [2, 'c']

8、 数组实例的 includes()

  • Array.prototype.includes方法返回一个布尔值,表示某个数组是否包含给定的值,
  • 不会误判 NaN
  • 该方法的第二个参数表示搜索的起始位置,默认为0
    • 如果第二个参数为负数,则表示倒数的位置。
    • 如果这时它大于数组长度(比如第二个参数为-4,但数组长度为3),则会重置为从0开始。
  • 没有该方法之前,我们通常使用数组的 indexOf 方法,检查是否包含某个值。
    • indexOf 方法有两个缺点:
      1. 不够语义化,它的含义是找到参数值的第一个出现位置,所以要去比较是否不等于-1,表达起来不够直观。
      2. 它内部使用严格相等运算符(===)进行判断,这会导致对 NaN 的误判。
  • 【点击打开demo
    let arr = ['a', 2, 'c', NaN];

    console.log(arr.includes(2)); // true
    console.log(arr.includes(NaN)); // true
    
    console.log(arr.indexOf(NaN)); // -1
  • 下面代码用来检查当前环境是否支持该方法,如果不支持,部署一个简易的替代版本。
const contains = (() =>
  Array.prototype.includes
    ? (arr, value) => arr.includes(value)
    : (arr, value) => arr.some(el => el === value)
)();
contains(['foo', 'bar'], 'baz'); // => false
  • 另外,MapSet 数据结构有一个 has 方法,需要注意与 includes区分。
    • Map 结构的 has 方法,是用来查找键名的,比如 Map.prototype.has(key)WeakMap.prototype.has(key)Reflect.has(target, propertyKey)
    • Set 结构的 has方法,是用来查找值的,比如 Set.prototype.has(value)WeakSet.prototype.has(value)

9、数组的空位

9.1 数组的空位是什么

  • 数组的空位指,数组的某一个位置没有任何值。
    • 空位不是 undefined,一个位置的值等于undefined,依然是有值的。
    • 空位是没有任何值,in运算符可以说明这一点。
  • 【点击打开demo
Array(3) // [, , ,],。

0 in [undefined, undefined, undefined] // true
0 in [, , ,] // false

9.2 ES5 对空位的处理

  • 大多数情况下会忽略空位。
    • forEach(), filter(), every()some()都会跳过空位。
    • map()会跳过空位,但会保留这个值
    • join()toString()会将空位视为undefined,而undefinednull会被处理成空字符串。
  • 【点击打开demo
    // forEach
    [, 'a'].forEach((v, i) => {
      console.log(v, i);
      // a 1
    })

    // filter
    const result1 = ['b', , 'a'].filter((v, i) => {
       return true;
    });
    console.log(result1); //  ["b", "a"]

    // every
    const result2 = [, 'a'].every((x) => {
      return x === 'a';
    })
    console.log(result2); // true

    // some
    const result3 = [, 'a'].some((x) => {
      return x !== 'a';
    })
    console.log(result3); // false

    // map
    const result4 = [, 'a'].map((x) => {
      return 1;
    })
    console.log(result4); // [, 1]

    // join
    console.log([, 'a', undefined, null].join('#')); // #a##

    // toString()
    console.log([, 'a', undefined, null].toString()); // ,a,,

9.3 ES6 对空位的处理

  • ES6 则是明确将空位转为 undefined
    1. Array.from方法会将数组的空位,转为undefined,也就是说,这个方法不会忽略空位。
    2. 扩展运算符(…)也会将空位转为undefined
    3. copyWithin()会连空位一起拷贝。
    4. fill()会将空位视为正常的数组位置。
    5. for...of循环也会遍历空位。
    6. entries()keys()values()find()findIndex()会将空位处理成 undefined
  • 【点击打开demo
    // Array.from
    console.log(Array.from([1, , 3])); // [1, undefined, 3]

    // ...扩展符
    console.log(...[1, , 3]); // [1, undefined, 3]

    // copyWithin
    console.log([, 2, , 4].copyWithin(2, 0)); // [, 2, , 2]

    // for ... of
    for (let i of [, ,]) {
      console.log(i);
      // undefined
      // undefined
    }

对于本文内容有问题或建议的小伙伴,欢迎在文章底部留言交流讨论。