数组的扩展

2019-06-15  本文已影响0人  萘小蒽

1 . Array.from();

let arrayLike = {
     '0': 'a',
     '1': 'b',
     '2': 'c',
     length: 3
 };
//es5写法 
[].slice.call(arrayLike )
//es6写法 
Array.from(arrauLike); // ["a", "b", "c"]
Array.from('hello');//["h", "e", "l", "l", "o"]
let arrayLike = {
     '0': '1',
     '1': '2',
     '2': '3',
     length: 3
 };
Array.from(arrayLike,x=>x*x) // [1, 4, 9]

2 . Array.of();

 Array.of(3,11,8)  //[ 3, 11, 8 ]
 Array.of(3)  //[ 3 ]
 Array.of(3).length  // 1

3 . 数组实例 copyWithin();

数组的实例方法,copyWithin()将指定位置的成员拷贝到其他位置上
Array.prototype.copyWithin(target, start = 0 , end = this.length)
三个参数:

[ 1 , 2, 3, 4, 5 ].copyWithin(0, 3, 4 ) 
//[4, 2, 3, 4, 5]
[ 1 , 2, 3, 4, 5 ].copyWithin(0, 3 ) 
//[4, 5, 3, 4, 5]

4 . 数组实例 find() 、findIndex();

find()用于找出第一个符合条件的数组成员并返回该成员,不符合则返回undefined.

[1,3,4,5,6].find(v=>v>4) //5
[1,3,4,5,6].find(v=>v>7) //undefined

findIndex()用于找出第一个符合条件的数组成员并返回该成员的下标值(index),不符合则返回-1.

5 . 数组实例 entries()、keys()、values()`

entries()、keys()、values()用于遍历数组。三个方法都返回一个遍历器对象(后期给链接),可用for...of循环遍历。

三个方法的唯一区别在于:

  • entries()对键值对的遍历
for(let i of ['a','b','c'].entries()){
   console.log(i)
 }
//[0, "a"]
//[1, "b"]
//[2, "c"]
  • keys()是对键名的遍历
for(let i of ['a','b','c'].keys()){
   console.log(i)
 }
//0
//1
//2
  • values()是对键值的遍历
for(let i of ['a','b','c'].values()){
   console.log(i)
 }
//'a'
//'b'
//'c'

6 . 数组实例includes()

Array.prototype.includes()返回一个布尔值,表示某个数组是否包含给定的值,与字符串的includes()方法类似(其实是es7的);

var a = {b:[1, 2, 3] };
var arr = [1, a, 3 ];
arr.includes(a);  // true
arr.includes(1);  // true 
arr.includes(2);  // false
[1, 2, 3 ].includes(3, 1) //true
[1, 2, 3 ].includes(3, 3) //false
[1, 2, NaN ].includes(NaN) //true
[1, 2, 3 ].includes(2,-1)  // false

includes()indexOf()比起来 :indexOf内部使用的是严格相等运算符,这样导致NaN的误判(包含NaN的运算都是NaN,且(NaN===NaN)为false)


7 . 数组实例fill()

['a','b', 'c' ].fill(7)
///[7, 7, 7 ]
['a','b', 'c' ].fill(7, 1, 2);  
///[ 'a', 7, 'c]
上一篇 下一篇

猜你喜欢

热点阅读