简体   繁体   English

findIndex 返回未定义而不是数字

[英]findIndex returning undefined instead of number

I have the following code:我有以下代码:

const index = myArray.findIndex(
      (f) =>
        f.name === term1 ||
        f.name === term2
    );

As I am trying to debug in Chrome Dev Tools, if I set a breakpoint after this snippet, index always shows as undefined .当我尝试在 Chrome 开发工具中调试时,如果我在此代码段之后设置断点, index总是显示为undefined It was my understanding that findIndex should always return a number , the first index of the array where the condition is met, -1 if it is never met.我的理解是findIndex应该始终返回一个number ,即满足条件的数组的第一个索引,如果从未满足,则返回 -1。

If I break immediately after this code and use the console to manually type in the code but don't assign it to anything, the console shows the correct index number.如果我在此代码之后立即中断并使用控制台手动输入代码但未将其分配给任何内容,则控制台将显示正确的索引号。 The issue isn't with the item being found in the array.问题不在于在数组中找到的项目。 It is there, but in the debugger it will only show undefined.它在那里,但在调试器中它只会显示未定义。

Why is this code returning undefined rather than a number ?为什么此代码返回undefined而不是number

*I have tried this in Firefox and Edge. *我已经在 Firefox 和 Edge 中尝试过这个。 It is the same issue there as well.那里也是同样的问题。

Just expanding your code a bit I have:-我只是稍微扩展你的代码: -

const term1 = 'aaa';
const term2 = 'bbb';
const myArray = [ { name: 'ccc' }, { name: 'ddd' }, ];
const index = myArray.findIndex(
  (f) =>
    f.name === term1 ||
    f.name === term2
);
console.log(index);

I always get the expected output of -1, or as expected.我总是得到 -1 的预期 output,或如预期的那样。 I tried fiddling with various combinations and types - no go.我尝试摆弄各种组合和类型 - 没有 go。

In my environment your code works fine - so I would guess the problem lies elsewhere.在我的环境中,您的代码工作正常 - 所以我猜问题出在其他地方。

Sorry - this doesn't constitute an answer - just some input:-)抱歉 - 这不构成答案 - 只是一些输入:-)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM