ES6-数组的扩展

2018-12-27  本文已影响0人  吴高亮

扩展运算符;

扩展运算符(spread)是三个点(...);它好比rest参数的逆运算;将一个数组转为用逗号分隔的参数序列。

console.log(...[1,2,3]);//1 2 3;
console.log(1,...[2,3,4],5);//1 2 3 4 5;
[...document.querySelectAll('div')]
// ES5 的写法
Math.max.apply(null, [14, 3, 77])
// ES6 的写法
Math.max(...[14, 3, 77])
// 等同于
Math.max(14, 3, 77);

作用;

const a1=[1,2];
//写法一
const a2=[...a1];//使用扩展字符串;
//写法二;
const [...a2]=a1;
上面的两种写法,a2都是a1的克隆;
const arr1=['a','b'];
const arr2=['c'];
const arr3=['d','e'];
//ES5的合并数组;
arr1.concat(arr2,arr3);
//['a','b','c','d','e'];
//ES6的合并数组;
[...arr1,...arr2,...arr3];
不过合并过都是浅拷贝;

const [first,...rest]=[1,2,3,4,5];
first=1;
rest=[2,3,4,5];
const [first,...rest]=[];
first//undefined;
rest //[];
const [first,...rest]=['foo'];
first //'foo';
rest //[];
注意在使用结构的时候;扩展运算只能放在最后一个;
如下
const [first,...rest,last]=['1','2','3'];
这样就会报错;

结构可以将字符串转为真正的数组;
[...'hello'];
//['h','e','l','l','o'];

Arroy.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(arratLike);//['a','b','c'];

只要部署了iterator[迭代器]接口的数据;都可以使用Array.from进行转换成数组;

Array.from('hello');//['h','e','l','l','o'];

Array.of();用于将数值转化为数组;

Array.of('1','2','3');//['1','2','3'];

Array.of() // []
Array.of(undefined) // [undefined]
Array.of(1) // [1]
Array.of(1, 2) // [1, 2]

数组实例的findIndex方法的用法与find方法非常类似,返回第一个符合条件的数组成员的位置,如果所有成员都不符合条件,则返回-1。

[1, 5, 10, 15].findIndex(function(value, index, arr) {
  return value > 9;
}) // 2
['a', 'b', 'c'].fill(7, 1, 2)
// ['a', 7, 'c']
for(let index of ['a','b'].key()){
 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';

如果不使用for...of循环,可以手动调用遍历器对象的next方法,进行遍历;

let letter=['a','b','c'];
let entries=letter.entries();
console.log(entries.next().value);//[0,'a']
console.log(entries.next().value);//[1,'b']
console.log(entries.next().value);//[2,'c']
[1,2,[3,4]].flat();
如果要拉平多层的就往里面传值;如果不管有多少层嵌套,
都要转成一维数组,可以用Infinity关键字作为参数。
[1, [2, [3]]].flat(Infinity)
// [1, 2, 3]
上一篇 下一篇

猜你喜欢

热点阅读