ES数组常用方法总结

1.find( (element, index, array)=>{} )

返回数组中满足提供的测试函数的第一个元素的值。

1
2
3
4
5
var arr = [{id:1,name:"张三"},{id:2,name:"王五"}]
arr.find(item => {
return item.id === 1 //
})
查询结果:{id:1,name:"张三"}

2.findIndex( (element, index, array)=>{} )

返回数组中满足提供的测试函数的第一个元素的索引

1
2
3
4
5
6
7
8
arr.findIndex(item => {
return item.id === 1
})
查询得到下标为:0
arr.findIndex(item => {
return item.id === 2
})
试图查找id为2的记录,不存在返回-1

3.map( (currentValue, index, array)=>{} )

方法通过对每个数组元素执行函数来创建新数组,不会改变原数组

1
2
3
4
5
6
var numbers1 = [45, 4, 9, 16, 25];
var numbers2 = numbers1.map(myFunction);
// 参数(项目值,项目索引,数组本身)
function myFunction(value, index, array) {
return value * 2;
}

注意操作json数组的时候,使用运算符 ...来避免地址引用导致修改原数组。 #### 4.filter()

创建一个包含通过测试的数组元素的新数组.

1
2
3
4
5
6
var numbers = [45, 4, 9, 16, 25];
var over18 = numbers.filter(myFunction);

function myFunction(value, index, array) {
return value > 18;
}

5.forEach

常用数组操作方法

forEach被调用时不会改变调用它的数组,而回调函数可能会改变新数组,例如:

1
2
3
4
5
6
7
8
9
10
var replaceSpace = function(s) {
let a = s.split('')
a.forEach((item,index,b)=>{
if(item===' '){
b[index] = '%20' //这里改变原数组
}
})
return a.join('')
};
console.log(replaceSpace("We are happy."))