首页 > 解决方案 > 即使项目存在于数组中,findIndex() 也会返回 -1

问题描述

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

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
      }
    }
....

这是我得到的结果:

我:{主题:“卡片”,player_id:6547,card_type:“yellow_card”,src_id:1,帧:5077}

this.instructions: [{subject: "period", name: "period_1", start: 5031, frame: 5031, src_id: -1}, {subject: "card", player_id: 6547, card_type: "yellow_card", src_id :1,帧:5077}]

iToUpdateInde:-1

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

我错过了什么?我会很感激一些帮助!

标签: javascriptangulartypescript

解决方案


最后,我在这里找到了我的问题的答案: console.log 是异步还是同步 我的代码没有任何问题,问题可能来自我使用的开发工具版本。

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


推荐阅读