【问题标题】:findIndex() returns -1 even though item exists in the Array即使项目存在于数组中,findIndex() 也会返回 -1
【发布时间】:2019-05-09 09:37:06
【问题描述】:

这是我正在处理的功能的一部分:

this.instructions 是一个数组。

我特意添加了一些 console.log() 只是为了告诉你我在 this.instructions 数组中寻找的项目存在。

insertOrUpdateI(i, instruction_frame) {

    if (i.hasOwnProperty('src_id')) {
      let iToUpdateIndex = this.instructions.findIndex(known_i => known_i.src_id == i.src_id);
      console.log('i: ',i)
      console.log('this.instructions: ',this.instructions);
      console.log('iToUpdateIndex: ', iToUpdateIndex);
      if (iToUpdateIndex > -1) {
        let oldInstruction = this.instructions[iToUpdateIndex];
        this.instructions[iToUpdateIndex] = {...i, frame: oldInstruction.frame}; // don't update the frame
        this.reconstructMatchState({
          fetchFromBack: false,
          lastFrame: this.stream.lastCameraFrame,
          applyNow: true
        }).subscribe();
        return
      }
    }
....

这是我得到的结果:

i : {subject: "card", player_id: 6547, card_type: "yellow_card", src_id: 1, frame: 5077}

this.instructions: [{subject: "period", name: "period_1", start: 5031, frame: 5031, src_id: -1}, {主题:“卡片”,player_id:6547,card_type:“yellow_card”,src_id:1,帧:5077}]

iToUpdateInde: -1

但是,我有 i.src_id === 1 并且我的数组中有一个项目的 src_id == 1

我错过了什么?我将不胜感激!

【问题讨论】:

标签: javascript angular typescript


【解决方案1】:

为我工作here's a stackblitz example,尝试再发一次。

【讨论】:

  • 我做了一个新的服务,我发送了 2 个指令,第一个我得到 iToUpdateInde == -1,第二个我得到 iToUpdateInde == 1。
  • 哦,这很奇怪,我认为这应该是由于异步调用造成的!检查指令数组或其自身是否是从 Http 调用中检索到的,第一个可能失败,因为它是在从 http 调用收到响应之前执行的。
  • 尝试在 findIndex() 之前和之后执行 console.log() 以查看您的数据
  • 所以我的日志与我拥有的数据完全对应
  • 它仍然输出错误的答案?第二个 findIndex() 是对的吗?奇怪
【解决方案2】:

最后,我在这里找到了我的问题的答案: Is console.log async or sync 我的代码没有问题,问题可能来自我使用的开发工具版本。

根据我们使用的浏览器及其版本,console.log() 似乎有不同的行为。有时它可能具有异步行为,即使我们没有在其中传递任何回调!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-03
    • 1970-01-01
    • 1970-01-01
    • 2019-04-20
    • 1970-01-01
    • 1970-01-01
    • 2015-05-26
    • 2017-03-20
    相关资源
    最近更新 更多