ES6学习之数组扩展

扩展运算符...将数组分割为用逗号分割的参数序列)

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

可替换数组的apply写法:

function test(x,y,z){
    console.log(x,y,z)
}

var arg = [1,2,3];
test.apply(null,arg)    ////1 2 3
test(...arg) //1 2 3

扩展运算符的应用

  • 复制数组
const a = [1, 2];
//复制数组a
const b = [...a] //方法1
const [...b] = a; //方法2
  • 合并数组
const a = [1, 2];
const b = [3, 4];
const c = [...a, ...b]; //[ 1, 2, 3, 4 ]
  • 解构赋值连用(与解构赋值连用,生成数组)
const [first, ...rest] = [1, 2, 3, 4, 5, 6];
console.log(first); //1
console.log(rest); //[ 2, 3, 4, 5, 6 ]
  • 字符串转数组
const a = [..."hello"];
console.log(a) //[ 'h', 'e', 'l', 'l', 'o' ]
  • 实现了Iterator接口的对象转数组(只要具有 Iterator 接口的对象,都可以使用扩展运算符转为真正的数组)
let nodeList = document.querySelectorAll('div');
let array = [...nodeList];
  • Map 和 Set 结构,Generator 函数
let map = new Map(
    [
        [1, "hello"],
        [2, "ES6"],
        [3, "test"]
    ]
)
let arr1 = [...map.keys()]; //[ 1, 2, 3 ]
let arr2 = [...map.values()];   //[ 'hello', 'ES6', 'test' ]
let arr3 = [...map.entries()];  //[ [ 1, 'hello' ], [ 2, 'ES6' ], [ 3, 'test' ] ]

Array.from()(将类似数组的对象和可遍历的对象转化为数组,只要具有length属性都能转

let arrayLike = {
    '0': 'a',
    '1': 'b',
    '2': 'c',
    length: 3
};
let arr = Array.from(arrayLike); //[ 'a', 'b', 'c' ];

let str = "hello";
let arr2 = Array.from(str); //[ 'h', 'e', 'l', 'l', 'o' ]

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

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

Array.of()(用于将一组值转化为数组,基本可以代替Array()和new Array())

let a0 = Array(0)   //[]
let a1 = Array.of(0); //[0]

let b0 = Array.of(1, 2, 3) //[ 1, 2, 3 ]
let b1 = Array(1, 2, 3) //[ 1, 2, 3 ]
copyWithin()(将指定位置的成员复制到其他位置(会覆盖原有成员),然后返回当前数组。使用这个方法,会修改当前数组。)
Array.prototype.copyWithin(target, start = 0, end = this.length);
//接受三个参数
//target(必需):从该位置开始替换数据
//start(可选):从该位置开始读取数据,默认为0。如果为负值,表示倒数。
//end(可选):到该位置前停止读取数据,默认等于数组长度。如果为负值,表示倒数。
[1, 2, 3, 4, 5].copyWithin(0, 3)
// [4, 5, 3, 4, 5]

find()和findIndex()

  • find()(数组中寻找成员,返回找到的第一个成员,否则返回undefined)
[1, 4, -5, 10].find((n) => n < 0) // -5
  • findIndex() (数组中寻找成员,范围找到的该成员开始的第一个位置,否则返回-1)
[1, 5, 10, 15].findIndex(function(value, index, arr) {
  return value > 9;
}) // 2

fill()(使用给定值,填充一个数组)

['a', 'b', 'c'].fill(7)  // [7, 7, 7]
entries(),keys() 和 values()(keys()是对键名的遍历、values()是对键值的遍历,entries()是对键值对的遍历)
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"

includes()(数组中寻找数组成员,找到范围true,否则返回false)

[1, 2, 3].includes(2)     // true
[1, 2, 3].includes(4)     // false
[1, 2, NaN].includes(NaN) // true

接收第二个参数,表示开的的位置

[1,2,3].includes(2,2)   //false

 

posted @ 2017-11-02 10:45  枫叶布  阅读(216)  评论(0编辑  收藏  举报