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

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
  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值