es6数组扩展

1.Array.of()

Array.of用于将一组值,转换为数组。

  let arr = Array.of(3,4,7,9,11);
  console.log(arr);    //[3, 4, 7, 9, 11]

  let empty=Array.of();
  console.log('empty',empty);    //[]
}

只有当参数个数不少于 2 个时,Array()才会返回由参数组成的新数组。参数个数只有一个时,实际上是指定数组的长度。

Array(3) // [, , ,]

Array.of()生成的数组是不可遍历(iterable)的。

2.Array.from()

Array.from方法用于将两类对象转为真正的数组:类似数组的对象(array-like object)和可遍历(iterable)的对象(包括 ES6 新增的数据结构 Set 和 Map)。

下面是一个类似数组的对象,Array.from将它转为真正的数组。

let arrayLike = {
    '0': 'a',
    '1': 'b',
    '2': 'c',
    length: 3
};

// ES5的写法
var arr1 = [].slice.call(arrayLike); // ['a', 'b', 'c']

// ES6的写法
let arr2 = Array.from(arrayLike); // ['a', 'b', 'c']

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

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

3.数组实例的 fill()

fill方法使用给定值,填充一个数组。

{
  console.log([1,'a',undefined].fill(7)); //[7, 7, 7]
  console.log(['a','b','c','d','e'].fill(7,1,3));   //["a", 7, 7, "d", "e"]
//从位置1开始到位置3结束
}

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

entries()keys()values()——用于遍历数组。它们都返回一个遍历器对象,可以用for...of循环进行遍历,唯一的区别是keys()是对键名的遍历、values()是对键值的遍历,entries()是对键值对的遍历。

{
  for(let index of ['1','c','ks'].keys()){
    console.log('keys',index);
//keys 0
// keys 1
// keys 2
  }
  for(let value of ['1','c','ks'].values()){
    console.log('values',value);
//values 1
// values c
// values ks
  }
  for(let [index,value] of ['1','c','ks'].entries()){
    console.log(index,value);
//0 "1"
// 1 "c"
// 2 "ks"
  }
}

5.数组实例的 copyWithin()

数组实例的copyWithin方法,在当前数组内部,将指定位置的成员复制到其他位置(会覆盖原有成员),然后返回当前数组。也就是说,使用这个方法,会修改当前数组。

{
  console.log([1,2,3,4,5].copyWithin(0,3,4));
// [4, 2, 3, 4, 5]
//位置0被替换,替换值从位置3开始到位置4之前结束
}

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

数组实例的find方法,用于找出第一个符合条件的数组成员。它的参数是一个回调函数,所有数组成员依次执行该回调函数,直到找出第一个返回值为true的成员,然后返回该成员。如果没有符合条件的成员,则返回undefined

{
  console.log([1,2,3,4,5,6].find(function(item){return item>3}));     //4
  console.log([1,2,3,4,5,6].findIndex(function(item){return item>3}));     //3
}

7.数组实例的 includes()

方法返回一个布尔值,表示某个数组是否包含给定的值,与字符串的includes方法类似。ES2016 引入了该方法。

  console.log([1,2,NaN].includes(1));   //true
  console.log([1,2,NaN].includes(NaN));     //true
}

include可以在查找NaN,find不可以



猜你喜欢

转载自www.cnblogs.com/sunmarvell/p/9122910.html