对于js中的数组,还在用for 循环遍历数组吗?数组的一些用法你用对了吗? 下面介绍一些数组的正确用法。
1. arr.indexOf() : 返回给定元素的下标 不存在则返回-1
2.arr.includes() :判断数组中是否包含某元素,返回boolean值, true/false
3.使用arr.find() 替代arr.filter()
arr.find(callback): 参数为回调函数 查找数组中是否有某一元素 返回该元素item,找到后便不再往下找 不存在则返回undefined;
arr.filter(callback): 参数为回调函数 过滤出符合条件的元素形成新数组 [item1,item2,...] , 不存在则返回空数组[];
当需要查找的item 在数组中是唯一的时候,选择arr.find() 比arr.filter()性能更优,因为arr.find()会在找到该item时便不再往下找,而arr.filter()会将整个数组进行遍历。
示例:
const characters = [
{id:1,name:'ironman',env:'marvel'},
{id:2,name:'black_window',env:'marvel'},
{id:3,name:'captain_america',env:'dc_comics'},
{id:4,name:'captain_america',env:'dc_aomics'}
]
function getCharacter(name){
return character=>character.name===name; // character代表数组的每一项item
}
let newArr1=characters.filter(getCharacter("captain_america"));
console.log("newArr1",newArr1);
/*
[
{id: 3, name: "captain_america", env: "dc_comics"},
{id: 4, name: "captain_america", env: "dc_comics"}
]
*/
let item=characters.find(getCharacter("captain_america"));
console.log("item",item) // { id: 3, name: 'captain_america'}
4.使用arr.some() 替代arr.find()
arr.some(callback):返回boolean值 true/false 相比arr.includes(值) (不考虑第二个可选参数)的可操控性更强
当我们需要知道数组中是否存在一个元素时,使用arr.some(callback) 相比arr.find()更合适。
示例:
const characters = [
{id:1,name:'ironman',env:'marvel'},
{id:2,name:'black_window',env:'marvel'},
{id:3,name:'captain_america',env:'dc_comics'},
{id:4,name:'captain_america',env:'dc_aomics'}
]
function hasCharacterFrom(env){
return character=>character.env===env;
}
//{id:1,name:'ironman',env:'marvel'}
console.log("find",characters.find(hasCharacterFrom('marvel')))
console.log("some",characters.some(hasCharacterFrom('marvel'))) // true
5.使用arr.reduce 替代arr.filter与arr.map的组合
arr.reduce()允许你将过滤后切加工过的项放进累计器中累计器可以是需要待递增的数字、待填充的对象、待拼接的字符串或数组等。
const characters = [
{id:1,name:'ironman',env:'marvel'},
{id:2,name:'black_window',env:'marvel'},
{id:3,name:'captain_america',env:'dc_comics'},
{id:4,name:'captain_america',env:'dc_aomics'}
]
/*
[
{id:1,name:'ironman',env:'marvel',alsoSeenIn:['Avengers']},
{id:2,name:'black_window',env:'marvel',alsoSeenIn:['Avengers']}
]
*/
console.log("filter+map的组合",
characters
.filter(character=>character.env==='marvel')
.map( character=>Object.assign( {},character,{alsoSeenIn:['Avengers']} ) )
)
// []:初始值 acc:代表每一次的累加值 character:item
console.log("reduce",
characters.reduce((acc,character)=>{
return character.env==='marvel'? acc.concat(
{...character,alsoSeenIn['Avengers']} ) : acc;
},[])
)