The x.name and imgname have the same type (string) and the same value "cardpro_capsule_model_2". But why the findIndex() function return -1? Please explain it to me.
findPicture(imgname): number {
return this.infocardList.findIndex(x => {
x.name === imgname; // result in console:
console.log(imgname) // cardpro_capsule_model_2
console.log(typeof imgname) // string
console.log(typeof x.name) // string
console.log(x.name); // cardpro_capsule_model_2
})
}
Expect result will be index of the element in array not -1.
The x.name and imgname have the same type (string) and the same value "cardpro_capsule_model_2". But why the findIndex() function return -1? Please explain it to me.
findPicture(imgname): number {
return this.info.cardList.findIndex(x => {
x.name === imgname; // result in console:
console.log(imgname) // cardpro_capsule_model_2
console.log(typeof imgname) // string
console.log(typeof x.name) // string
console.log(x.name); // cardpro_capsule_model_2
})
}
Expect result will be index of the element in array not -1.
Share Improve this question edited Oct 16, 2019 at 14:19 CollinD 7,5832 gold badges24 silver badges47 bronze badges asked Oct 16, 2019 at 13:55 Tùng BillTùng Bill 1491 gold badge3 silver badges14 bronze badges 2- 2 you need add a return statement – juancarlos Commented Oct 16, 2019 at 13:58
-
1
Because you're NOT
returning
the result of the parison. That's all that's going on here. – Dženis H. Commented Oct 16, 2019 at 14:11
3 Answers
Reset to default 5Your findIndex
callback always returns undefined, you should instead return x.name === imgname;
The findIndex
function essentially does something like
if (findIndexCallback(element)) return index;
for each element of the array. So if your function returns nothing (undefined
), the fallback value of -1
meaning "not found" is returned.
See https://developer.mozilla/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex for full documentation.
you need add a return statement on your findIndex
findPicture(imgname): number {
return this.info.cardList.findIndex(x => {
return x.name === imgname; // result in console:
})
}
You need to return the result from your findIndex function.
findPicture(imgname): number {
return this.info.cardList.findIndex(x => {
return x.name === imgname;
});
}
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745143023a4613516.html
评论列表(0条)