程序员

ES6学习笔记六|数组的扩展

2016-11-02  本文已影响52人  ForeverYoung20

1. Array.from()

Array.from(arrayLike, x => x * x);
//等同于
Array.from(arrayLike).map(x => x * x);

Array.from([1,2,3], (x) => x * x)
// [1,4,9]
 function countSymbols(string) {
     return Array.from(string).length;
 }

2. Array.of()

Array.of(3,11,5);   //[3,11,5]
Array.of(2).length;   //1

3. 数组实例的copyWithin()

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

Array.prototype.copyWithin(target,start=0,end=this.length)
[1,2,3,4,5].copyWithin(0,3)
//[4,5,3,4,5]

4. 数组实例的find()和findIndex()

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

这两个方法都可接受第二个参数,用来绑定回调函数的this对象。

5. 数组实例的fill()

['a','b','c'].fill(7)    //[7,7,7]
['a','b','c'].fill(8,1,2)   //['a',8,'c']

6. 数组实例的entries(),keys()和values()

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"

7. 数组实例的includes()

8. 数组的空位

Array(3)  //[ , , ]

注意:空位不是undefined,空位是没有任何值。

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

总结:

上一篇 下一篇

猜你喜欢

热点阅读