4. 数组

2018-02-24 16:11 更新
  • 4.1 使用字面值创建数组。

    // bad
    const items = new Array();
    
    // good
    const items = [];
  • 4.2 向数组添加元素时使用 Arrary#push 替代直接赋值。

    const someStack = [];
    
    // bad
    someStack[someStack.length] = 'abracadabra';
    
    // good
    someStack.push('abracadabra');
  • 4.3 使用拓展运算符 ... 复制数组。

    // bad
    const len = items.length;
    const itemsCopy = [];
    let i;
    
    for (i = 0; i < len; i++) {
      itemsCopy[i] = items[i];
    }
    
    // good
    const itemsCopy = [...items];
  • 4.4 使用 Array#from 把一个类数组对象转换成数组。

    const foo = document.querySelectorAll('.foo');
    const nodes = Array.from(foo);
以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号