为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

泛舟湖上清波郎朗 2022-01-07 10:49:39
我没有找到以下问题的解决方案。在这种情况下,索引一直返回 -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)
查看完整描述

3 回答

?
呼如林

TA贡献1798条经验 获得超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)


查看完整回答
反对 回复 2022-01-07
?
慕标琳琳

TA贡献1830条经验 获得超9个赞

您需要添加退货。


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)


查看完整回答
反对 回复 2022-01-07
?
慕哥9229398

TA贡献1877条经验 获得超6个赞

正如@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)


查看完整回答
反对 回复 2022-01-07
  • 3 回答
  • 0 关注
  • 657 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信