您的位置:首页 > 其它

ES6学习笔记(ES6新增的数组方法)

2017-11-09 16:58 459 查看

1、Array.from()方法

Array.from()方法是用于类似数组的对象(即有length属性的对象)和可遍历对象转为真正的数组。

比如,使用Array.from()方法,可以轻松将JSON数组格式转为数组。

let json ={
'0':'hello',
'1':'123',
'2':'panda',
length:3
}
let arr = Array.from(json);
console.log(arr);


控制台打印结果:
["hello", "123", "panda"]


2、使用Array.of()方法

Array.of()方法是将一组值转变为数组。

let arr0 = Array.of(1,2,33,5);
console.log(arr0);//[1,2,33,5]

let arr1 = Array.of('你好','hello');
console.log(arr1);//["你好", "hello"]


3、find()方法

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

如:回调函数可以接收3个参数,依次为当前的值(value)、当前的位置(index)、原数组(arr)

let arr2 = [1,2,3,5,7];
console.log(arr2.find(function(value,index,arr2){
return value > 5;
}))


控制台打印结果:
7


4、fill()方法

使用fill()方法给定值填充数组。

fill方法用于空数组的初始化很方便:
new Array(3).fill(7);//[7,7,7]


fill方法还可以接收第二个和第三个参数,用于指定填充的起始位置和结束位置:

let arr3 = [0,1,2,3,4,5,6,7];
arr3.fill('error',2,3);
console.log(arr3);//[0,1,"error",3,4,5,6,7]


5、遍历数组的方法:entries()、values()、keys()

这三个方法都是返回一个遍历器对象,可用
for...of
循环遍历,唯一区别:keys()是对键名的遍历、values()对键值的遍历、entries()是对键值对的遍历。

for(let item of ['a','b'].keys()){
consloe.log(item);
//0
//1
}
for(let item of ['a','b'].values()){
consloe.log(item);
//'a'
//'b'
}
let arr4 = [0,1];
for(let item of arr4.entries()){
console.log(item);
//  [0, 0]
//  [1, 1]
}
for(let [index,item] of arr4.entries()){
console.log(index+':'+item);
//0:0
//1:1
}


如果不用
for...of
进行遍历,可用使用next()方法手动跳到下一个值。

let arr5 =['a','b','c']
let entries = arr5.entries();
console.log(entries.next().value);//[0, "a"]
console.log(entries.next().value);//[1, "b"]
console.log(entries.next().value);//[2, "c"]
console.log(entries.next().value);//undefined
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: