ES6数组方法总结
ES6数组方法
forEach() 遍历
数组名.forEach(function(数组中一个元素的值){对这个值进行处理…})
var col = ["a","b","c"];
for(var i = 0; i < col.length; i++){
console.log('数组遍历1--',col[i]); // a,b,c
}
col.forEach(function(item){
console.log('数组遍历2--',item); //a,b,c
})
col.forEach((item) => {
console.log('数组遍历3--',item); //a,b,c
})
map() 映射,返回一个新数组或undefined,原数组不变
var a = [1,2,3];
var a1 = [];
for(var i = 0; i<a.length; i++){
a1.push(a[i]*2);
}
console.log('a1:',a1) // [2,4,6]
var a2 = a.map((item) => {
return item*2;
})
console.log('a2:',a2) // [2,4,6]
var b = [
{name: "lisi", age: 23},
{name: "tony", age: 25}
]
var b1 = b.map((item) => {
return item.name+"----"
})
console.log(b1) // ["lisi----", "tony----"]
filter() 过滤,返回满足条件的新数组,不改变原数组
var c = [
{name: "lisi", age: 23, type: 'person', count: 0},
{name: "tony", age: 25, type: 'person', count: 4},
{name: "he", age: 3, type: 'cat', count: 1},
{name: "bai", age: 1, type: 'cat', count: 7}
]
var c1 = c.filter((item) => {
return item.type === "cat";
})
console.log(c) // 不变
console.log(c1) // [{name: "he", age: 3, type: 'cat'},{name: "bai", age: 1, type: 'cat'}]
c = c.filter((item) => {
return item.type === "person" && item.count > 3
})
console.log(c) //[{name: "tony", age: 25, type: 'person', count: 4}]
find() 查找,返回找到的第一个满足条件的新数组,找到之后就会直接返回,不继续找
var d = [
{name: "lisi", age: 23, type: 'person', count: 0},
{name: "tony", age: 25, type: 'person', count: 4},
{name: "he", age: 3, type: 'cat', count: 1},
{name: "he", age: 1, type: 'cat', count: 7}
]
d = d.find( item => item.name === "he" )
console.log(d) //[{name: "he", age: 3, type: 'cat', count: 1}]
实际开发应用环境:博客列表,点击博客列表,根据博客列表的URL的数组,用find找到对应的Id,然后找到对应的列表的详情页的URL,并进行展示
some() 某一个满足返回true,every()所有都满足才返true
var e = [
{name: "lisi", age: 16},
{name: "lisi2", age: 23},
{name: "lisi3", age: 11},
{name: "tony", age: 20}
]
var some = e.some(item => item.age < 18)
console.log(some) // true
var every = e.every(item => item.age < 18)
console.log(every) // false
reduce() 从左到右累加
对数组中的所有元素调用指定的回调函数。该回调函数的返回值为累积结果,并且此返回值在下一次调用该回调函数时作为参数提供
(1)代替map()做一些简单的运算
var f = [10, 20, 30];
var f1 = f.reduce((sum, num) => {
console.log('sum--1', sum) // 0, 10, 30
console.log('num--2', num) // 10, 20, 30
return sum + num;
}, 0) // 初始化sum = 0
console.log(f1) // 60
(2)将对象数组中的某些属性的值抽出来,形成新数组
var col = [
{name: "liming", age: 23},
{name: "zhaosi", age: 18},
{name: "wangwu", age: 26},
]
var col2 = col.reduce((colArr, item) => {
console.log('colArr--1', colArr); // [], ["liming"], ["liming", "zhaosi"]
colArr.push(item.name)
console.log('colArr--2', colArr); // ["liming"], ["liming", "zhaosi"], ["liming", "zhaosi", "wangwu"]
return colArr
}, []) // 初始化colArr = []
console.log(col2) // ["liming", "zhaosi", "wangwu"]