findIndex() 总是在带有对象的数组上返回-1

我没有找到以下问题的解决方案。在这种情况下,索引一直返回 -1 而不是 1。


任何人都可以帮助我吗?


let allRules = [{ruleName: "a"}, {ruleName: "b"}, {ruleName: "c"}]

let name = "b"

let index = allRules.findIndex(x => {

  console.log(x.ruleName)

  x.ruleName === name

})

console.log(index)


泛舟湖上清波郎朗
浏览 658回答 3
3回答

呼如林

您需要在回调方法中使用return关键字{}:let allRules = [{ruleName: "a"}, {ruleName: "b"}, {ruleName: "c"}]let name = "b"let index = allRules.findIndex(x => {  console.log(x.ruleName)  return x.ruleName == name})console.log(index)一个没有return声明的例子:let allRules = [{ruleName: "a"}, {ruleName: "b"}, {ruleName: "c"}]let name = "b"let index = allRules.findIndex(x => x.ruleName == name)console.log(index)

慕标琳琳

您需要添加退货。let allRules = [{ruleName: "a"}, {ruleName: "b"}, {ruleName: "c"}]let name = "b"let index = allRules.findIndex(x => {  console.log(x.ruleName)  return x.ruleName === name})console.log(index)

慕哥9229398

正如@Nick Parsons 在评论中所说,你需要return一些东西。let allRules = [{ruleName: "a"}, {ruleName: "b"}, {ruleName: "c"}]let name = "b"let index = allRules.findIndex(x => {  console.log(x.ruleName);  return x.ruleName === name;})console.log(index)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript