【问题标题】:Comparing two Objects not working? [duplicate]比较两个对象不起作用? [复制]
【发布时间】:2018-03-29 12:28:20
【问题描述】:

我在比较两个对象时遇到了问题。

我将传入的对象与对象数组进行比较, 查看对象是否已经在数组中。

我尝试了两种方法:

(betTemps 是对象数组,tempBet 是当前要比较的对象。)

var duplicate = false;
for (let bet of this.betTemps) {
console.log(tempBet);
  console.log(bet);
  if(bet === tempBet) {
    console.log("reached");
    duplicate = true;
    break;
  }
}

如果之后:

.. else if(duplicate){
  alert("The Bet is already in the List");
} ...

添加一个已经在数组中的对象后的控制台输出:

控制台输出截图

如您所见,它们是相等的,但另一个 Object 仍被添加到数组中。

我也尝试使用 indexOf 使用此方法:

if(this.betTemps.indexOf(tempBet) > -1){
  alert("The Bet is already in the List");
}

添加一个已经在数组中的对象后的控制台输出:

控制台输出截图

PS:

对比前的代码:

  addBet(bet, index){
var tempBet = Object.assign({}, bet);
var select = (document.getElementById('select'+index)) as HTMLSelectElement;
select = select.options as HTMLSelectElement;
let count = 0;

tempBet.category = [];
for(let i = 0; i < 3; i++) {
    if (select[i].selected) {
      tempBet.category.push(select[i].value):
      count++;
    }
}

对比后的代码:

if (count == 0) {
  alert("There has to be at least one Category choosen!");
} else if(duplicate     <- This part changes individually which method you use ->){
  alert("The Bet is already in the List");
} else {
  this.betTemps.push(tempBet);
}

【问题讨论】:

    标签: javascript jquery object comparison


    【解决方案1】:

    检查对象是否在数组中的最好方法是使用数组包含函数: 就像如果我想检查 A 对象是否在 B 数组中,我会检查 (A === B.includes(A))

    【讨论】:

      猜你喜欢
      • 2015-09-11
      • 2021-08-05
      • 1970-01-01
      • 1970-01-01
      • 2013-10-02
      • 1970-01-01
      • 1970-01-01
      • 2017-09-23
      • 1970-01-01
      相关资源
      最近更新 更多