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
相关文章推荐
- es6 Array数组对象新增方法 Array.of()
- ES6---数组array新增方法
- es6 数组对象新增方法 Array.from()将两类对象转为真正的数组
- ES6中数组array新增方法实例总结
- JS 中 原生方法 (二) --- 数组 (修---添加ES6新增)
- ES6数组新增的几个方法
- ES6中新增数组方法与ES5之间的区别
- es6新增的数组去重方法
- es5中新增的数组方法
- JS中数组的常用方法(包含es6扩展)
- ES6循环数组新方法for-of(转)
- es6数组新增东西
- ES6---string新增方法
- ES5中数组新增的方法说明
- 理解 ES6 --- 数组新方法
- es6 数组扩展方法
- Es6中如何使用splic,delete等数组删除方法
- ES6中新增的Object.assign()方法详解
- 再不用ES6就Out了--Object中新增的几个方法
- Javascript 1.6 数组新增方法介绍之 forEach()