findIndex返回-1,但它应该返回0

时间:2018-05-29 11:52:52

标签: javascript

console.log(books[0]._id);
console.log(user.bookRecomendations);
const index = user.bookRecomendations.findIndex( x => x.bookId === books[0]._id);
console.log(index);

它在控制台中返回:

5b0685e238e2e50ba4c10d49

[{"bookId":"5b0685e238e2e50ba4c10d49","rating":900},{"bookId":"5b0949a3b7c9170be08aa6b5","rating":900},{"bookId":"5b0708dbf1079d0dfa98489b","rating":900},{"bookId":"5b0948947c110b0ba9069327","rating":1600}]

-1

as user.bookRecomendations [0] .bookId与book [0]具有相同的值._ id它应该返回0,但它仍然没有,并且显示-1,因为它不匹配。任何建议如何修复它并得到user.bookRecomendations的索引,bookId等于books [0] ._ id?

编辑:

console.log('['+books[0]._id+']');
console.log('['+user.bookRecomendations[0].bookId+']’);
console.log(books[0]._id===user.bookRecomendations[0].bookId);

返回:

[5b0685e238e2e50ba4c10d49]
[5b0685e238e2e50ba4c10d49]
false

1 个答案:

答案 0 :(得分:0)

好的,问题在于类型,书籍[0] ._ id和user.bookRecomendations [0] .bookId都是对象。 所以比较

books[0]._id.toString() === user.bookRecomendations[0].bookId.toString() 

完美运作