zoukankan      html  css  js  c++  java
  • ECMA Script 6_数组的扩展_扩展运算符

    1. 扩展运算符

    内部调用的是数据结构的 Iterator 接口,

    因此只要具有 Iterator 接口的对象,都可以使用扩展运算符 ...

    如 map,,,,

    [...arr]

    扩展运算符(spread)是三个点(...)

    将一个数组转为用逗号分隔的参数序列

    • console.log(...[1, 2, 3]);    // 1 2 3
      
      console.log(1, ...[2, 3, 4], 5);    // 1 2 3 4 5
      
      [...document.querySelectorAll('div')];    // [<div>, <div>, <div>]
    • 主要用于函数调用
    • function push(array, ...items) {
          array.push(...items);
      };
      
      function add(x, y) {
          return x + y;
      };
      
      const numbers = [4, 38];
      add(...numbers);    // 42
    • 扩展运算符后面还可以放置表达式
    • const arr = [
        ...(x > 0 ? ['a'] : []),
        'b',
      ];
    • 如果扩展运算符后面是一个空数组,则不产生任何效果
    • [...[], 1];    // [1]
    • 不再需要apply方法,将数组转为函数的参数了
    • function f(x, y, z) {
        // ...
      }
      
      f.apply(null, [0, 1, 2]);    // ES5 的写法
      
      f(...[0, 1, 2]);    // ES6的写法
    • Math.max.apply(null, [14, 3, 77]);    // ES5 的写法
      
      
      Math.max(...[14, 3, 77]);    // ES6 的写法
      
      // 等同于
      Math.max(14, 3, 77);;    
    • var arr1 = [0, 1, 2];
      var arr2 = [3, 4, 5];
      
      Array.prototype.push.apply(arr1, arr2);    // ES5 的写法
      
      arr1.push(...arr2);    // ES6 的写法

    2. 复制数组 ...

    ES5 只能用变通方法来复制数组

    • const a1 = [1, 2];
      const a2 = a1.concat();
      
      a2[0] = 2;
      a1    // [1, 2]
    • ES6 使用 ...复制数组        但还是浅拷贝
    • const a1 = [1, 2];
      
      const a2 = [...a1];    // 写法一
      
      const [...a2] = a1;    // 写法二

    如果将扩展运算符用于数组赋值,只能放在参数的最后一位,否则会报错

    • 扩展运算符还可以将字符串转为真正的数组
    • [...'hello'];    // [ "h", "e", "l", "l", "o" ]

      好处,那就是能够正确识别四个字节的 Unicode 字符。

    • 'xuD83DuDE80y'.length     // 4
      [...'xuD83DuDE80y'].length     // 3    正确返回字符串长度的函数

    正确返回字符串长度

    • function length(str) {
          return [...str].length;
      };
      
      length('xuD83DuDE80y');    // 3

    3. Array.from()

    Array.from() 用于将以下两类对象转为真正的数组

    • 类似数组的对象(array-like object)
    • 遍历(iterable)的对象(包括 ES6 新增的数据结构 Set 和 Map)

    任何有 length 属性的对象,都可以通过 Array.from() 转为数组,而弥补 扩展运算符 ... 就无法转换

    因为 扩展运算符... 只对有 Iterator 接口的对象, 转为真正的数组

    • 实例
    • let arrayLike = {
          '0': 'a',
          '1': 'b',
          '2': 'c',
          length: 3
      };
      
      var arr1 = [].slice.call(arrayLike); // ['a', 'b', 'c']    // ES5的写法
      
      let arr2 = Array.from(arrayLike); // ['a', 'b', 'c']    // ES6的写法
    • querySelectorAll() 返回的是一个 NodeList 对象。它不是数组,而是一个类似数组的对象。

    这时,扩展运算符可以将其转为真正的数组,原因就在于 NodeList 对象实现了 Iterator

    • let nodeList = document.querySelectorAll('div');
      
      let array
      = [...nodeList];

      let arr = Array.from(nodeList);
    • 字符串转数组,Set 对象 转 数组
    • Array.from('hello');    // ['h', 'e', 'l', 'l', 'o']
      
      let namesSet = new Set(['a', 'b']);
      Array.from(namesSet);    // ['a', 'b']

    4. Array.from() 还可以接受第二个参数,作用类似于数组的map方法,用来对每个元素进行处理,将处理后的值放入返回的数组

    • Array.from(arrayLike, x => x * x);
      
      // 等同于
      Array.from(arrayLike).map(x => x * x);
      
      
      Array.from([1, 2, 3], (x) => x * x);    // [1, 4, 9]
    • 将数组中 布尔值为 false 的成员转为 0
    • Array.from([1, , 2, , 3], (n) => n || 0);    // [1, 0, 2, 0, 3]
    • 返回各种数据的类型
    • function typesOf () {
          return Array.from(arguments, value => typeof value)
      };
      typesOf(null, [], NaN);    // ['object', 'object', 'number']
    • 完美计算 length
    • function countSymbols(string) {
          return Array.from(string).length;
      }:

      因为它能正确处理各种 Unicode 字符,可以避免 JavaScript 将大于uFFFF的 Unicode 字符,算作两个字符的 bug

    • 传入 Array.from() 第三个参数,用来绑定 this

    4. Array.of

    将一组值,转换为数组

    • Array.of(3, 11, 8);    // [3,11,8]
      Array.of(3);    // [3]
      Array.of(3).length;    // 1
    • 基本上可以用来替代 Array() 或 new Array(),并且 不存在 由于 参数不同 导致重载。它的行为非常统一
    • Array.of();    // []
      Array.of(undefined);    // [undefined]
      Array.of(1);    // [1]
      Array.of(1, 2);    // [1, 2]

    5. 数组实例的 Array.prototype.copyWithin(target, start = 0, end = this.length)

    数组实例的 arr.copyWithin()

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

    也就是说,使用这个方法,会修改当前数组。

    target(必需)        从 target 开始替换数据。如果为负值,表示倒数。
    start(可选)       从 start 开始读取数据,默认为 0。如果为负值,表示倒数。
    end(可选)       到 end 前停止读取数据,默认等于数组长度。如果为负值,表示倒数。

    这三个参数都应该是数值,如果不是,会自动转为数值

    • [1, 2, 3, 4, 5].copyWithin(0, 3);    // [4, 5, 3, 4, 5]
    • // 将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号位
      let 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]

    6. arr.find()

    找出第一个符合条件的数组成员

    它的参数是一个回调函数,所有数组成员依次执行该回调函数,直到找出第一个返回值为 true 的成员,然后返回该成员

    如果没有符合条件的成员,则返回 undefine

    • [1, 4, -5, 10].find((n) => n < 0);    // -5
    • [1, 5, 10, 15].find(function(ele, index, arr) {
          return ele > 9;
      });    // 10

    7. arr.findIndex()

    返回第一个符合条件的数组成员的位置

    如果所有成员都不符合条件,则返回-1

    • [1, 5, 10, 15].findIndex(function(value, index, arr) {
          return value > 9;
      });    // 2
    • arr.find() arr.findIndex() 都可以接受第二个参数,用来绑定回调函数的this对象
    • let person = {name: 'John', age: 20};
      [10, 12, 26, 15].find(function(ele){
          return v > this.age;
      }, person);    // 26
    • arr.find() 和 arr.findIndex() 都可以发现NaN,弥补了数组的 indexOf 方法的不足

    内部其实借助 Object.is 发现了 NaN

    8. arr.fill() 

    使用给定值填充一个数组

    第一个参数: 给定值

    第二个参数: 填充起始位置

    第三个参数: 填充结束位置        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']
    • 用于空数组的初始化非常方便。数组中已有的元素,会被全部抹去
    • 如果填充的类型为对象,那么被赋值的是同一个内存地址的对象,而不是深拷贝对象
    • let arr = new Array(3).fill({name: "Mike"});
      arr[0].name = "Ben";
      console.log(arr);    // [{name: "Ben"}, {name: "Ben"}, {name: "Ben"}]
      
      let arr = new Array(3).fill([]);
      arr[0].push(5);
      console.log(arr);    // [[5], [5], [5]]

    9. ES6 遍历数组新方法

    都返回一个遍历器对象,可以用 for...of 循环进行遍历

    arr.entries()        是对键值对的遍历

    arr.keys()        是对键名的遍历

    arr.values()        是对键值的遍历

    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 ele of ['a', 'b'].values()) {
          console.log(ele);
      };
      // 'a'
      // 'b'
    • 不使用 for...of 循环,可以手动调用遍历器对象的 next() 方法,进行遍历
    • let letter = ['a', 'b', 'c'];
      let entries = letter.entries();
      console.log(entries.next().value);    // [0, 'a']
      console.log(entries.next().value);    // [1, 'b']
      console.log(entries.next().value);    // [2, 'c']

    10. arr.includes()

    返回一个布尔值,表示某个数组是否包含 给定值,与字符串的 includes 方法类似

    第一个参数: 给定值

    第二个参数: 表示搜索的起始位置,默认为 0

    如果第二个参数为负数,则表示倒数的位置,

    如果这时它大于数组长度(比如第二个参数为-4,但数组长度为3),则会重置为从 0 开始

    • [1, 2, 3].includes(2);     // true
      [1, 2, 3].includes(4);     // false
      [1, 2, NaN].includes(NaN);    // true
    • Map 和 Set 数据结构有一个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)

    11. arr.flat()

    将嵌套的数组 "拉平",变成一维的数组。该方法返回一个新数组,对原数据没有影响

    • [1, 2, [3, 4]].flat();    // [1, 2, 3, 4]

    arr. flat() 只有一个参数,指定“拉平” 多少层,默认为1

    传递一个整数,表示想要拉平的层数,

    如果不管有多少层嵌套,都要转成一维数组,可以用 Infinity 关键字作为参数

    • [1, 2, [3, [4, 5]]].flat();    // [1, 2, 3, [4, 5]]
      
      [1, 2, [3, [4, 5]]].flat(2);    // [1, 2, 3, 4, 5]

      [1, [2, [3]]].flat(Infinity);    // [1, 2, 3]

    • 如果原数组有空位,arr.flat() 处理后会去掉
    • [1, 2, , 4, 5].flat();    // [1, 2, 4, 5]

    12. arr.flatMap()

    对原数组的每个成员执行一个函数(相当于执行Array.prototype.map()),

    然后对返回值组成的数组 arr 执行 arr.flat()方法。

    该方法返回一个新数组,不改变原数组

    参数:

    第一个参数: 回调函数

    第二个参数: 绑定 this 指向

    • // 相当于 [[[2]], [[4]], [[6]], [[8]]].flat()
      [1, 2, 3, 4].flatMap(x => [[x * 2]]);    // [[2], [4], [6], [8]]

    13. 数组的空位

    数组的某一个位置没有任何值。比如,Array 构造函数返回的数组都是空位

    ES5 对空位的处理,已经很不一致了,大多数情况下会忽略空位

    ES6 则是明确将空位转为 undefined,而不会忽略空位

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

     

    --------小尾巴 ________一个人欣赏-最后一朵颜色的消逝-忠诚于我的是·一颗叫做野的心.决不受人奴役.怒火中生的那一刻·终将结束...
  • 相关阅读:
    kvm添加磁盘
    python学习1
    ubuntu使sudo不需要密码
    磁盘挂载
    github/gitlab添加多个ssh key
    生成SSH key
    git 删除追踪状态
    angular2+ 初理解
    本地项目上传到GitHub
    new Date()之参数传递
  • 原文地址:https://www.cnblogs.com/tianxiaxuange/p/10126991.html
Copyright © 2011-2022 走看看