數(shù)據(jù)是這樣的:var obj = [
{
id:1,
name:"小明"
},
{
id:2,
name:"小紅"
},
{
id:3,
name:"小雷"
}];我現(xiàn)在想知道name為‘小紅’的下標(biāo)是多少//數(shù)組,要找的字段,要找的內(nèi)容function findIndex(arr,key,word){
arr.map((o,n)=>{ if(o[key] == word){ return n;
}
})
}var t = findIndex(obj,'name','小紅');console.log(t); //underfine
2 回答

繁花如伊
TA貢獻(xiàn)2012條經(jīng)驗(yàn) 獲得超12個(gè)贊
map中的return是返回到map數(shù)組當(dāng)中。即題中arr.map跑完時(shí)被賦值為[undedined,1,undefined]。所以你的findindex返回的是一個(gè)空值。你可以在arr.map之前加一個(gè)return就可以看到返回值值了。
可以改成這個(gè)樣子,就可以了。
function findIndex(arr,key,word){ arr.map((o,n)=>{ if(o[key] == word){ console.log(n); } }); }
添加回答
舉報(bào)
0/150
提交
取消