文章目录
  1. 1. 字符串的扩展
  2. 2. 数组

    根据阮一峰老师《ECMAScript 6入门》的ES6学习笔记。

字符串的扩展

  1. ES6之前,对于4个字节的字符,js不能正确处理,字符串长度会误判为2, charAt无法读取整个字符
    ES6提供了codePointAt方法,能够正确处理4个字节储存的字符,返回一个字符的码点
  2. codePointAt方法用于 for…of 循环时 能正确识别4字节码长度
  3. 测试一个字符是两个字节还是四个字节的最简单的方法

    1
    2
    3
    4
    5
    6
    7
    var a= "好";
    for(let ch of a){
    console.log(ch.codePointAt(0).toString(16));
    }
    function is32Bit(c){
    return c.codePointAt(0) > 0xFFFF;
    }
  4. ES5提供String.fromCharCode方法,用于从码点返回对应字符,但是这个方法不能识别32位的UTF-16字符(Unicode编号大于0xFFFF)。
    ES6提供了String.fromCodePoint方法,可以识别大于0xFFFF的字符

  5. ES5对字符串对象提供charAt方法,返回字符串给定位置的字符。该方法不能识别码点大于0xFFFF的字符。
    ES6提供了at方法,可以返回大于0xFFFF的字符。
  6. 除了之前的indexOf() 方法 新增includes() startsWith() endsWith() 方法。
  7. padStartpadEnd多用于不全指定位数,或提箱字符串格式

    1
    2
    3
    4
    5
    6
    '1'.padStart(10, '0') // "0000000001"
    '12'.padStart(10, '0') // "0000000012"
    '123456'.padStart(10, '0') // "0000123456"
    '12'.padStart(10, 'YYYY-MM-DD') // "YYYY-MM-12"
    '09-12'.padStart(10, 'YYYY-MM-DD') // "YYYY-09-12"
  8. 模板字符串

    1
    2
    3
    4
    5
    $('#result').append(`
    There are <b>${basket.count}</b> items
    in your basket, <em>${basket.onSale}</em>
    are on sale!
    `);

数组

  1. Array.from方法用于将两类对象转为真正的数组:类似数组的对象(array-like object)和可遍历(iterable)的对象(包括ES6新增的数据结构Set和Map);
    Array.from可以有第二个参数,作用类似于map方法

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

    ES5的写法: var a= [].slice.call(array-like);

    另外 扩展运算符(…)也可以将某些数据结构转为数组。

  2. Array.of()将一组值转化为数组 ,弥补构造函数Array()的不足

    1
    2
    3
    4
    5
    6
    Array.of(3, 11, 8) // [3,11,8]
    Array.of(3) // [3]
    Array.of(3).length // 1
    Array() // []
    Array(3) // [, , ,]
    Array(3, 11, 8) // [3, 11, 8]
  3. copyWithin()

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    // 将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}
  4. find()用于找出第一个符合条件的数组成员

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

    数组实例的findIndex方法的用法与find方法非常类似,返回第一个符合条件的数组成员的位置,如果所有成员都不符合条件,则返回-1。includes() 表示某个数组是否包含给定的值,这三个方法都能比较好的处理NaN 的问题。

  5. entries(),keys(),values()keys()是对键名的遍历、values()是对键值的遍历,entries()是对键值对的遍历。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    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 [index, elem] of ['a', 'b'].entries()) {
    console.log(index, elem);
    }
    // 0 "a"
    // 1 "b"
  6. 注意数组的空位问题,即[,,,]多个函数对空位的处理都不同

文章目录
  1. 1. 字符串的扩展
  2. 2. 数组