2015-09-04 76 views
0

所以我试图编写一些代码来检查两个人是否共享相同的生日。正如你所看到的人“一个”和个人“B”不共享同一天生日,但在控制台上输出是:比较同一对象中的值

a was born on day 1 
a has the same birthday as a 
a has the same birthday as b 
b was born on day 2 
b has the same birthday as a 
b has the same birthday as b 

,而应该是:

a was born on day 1 
a has the same birthday as a 
b was born on day 2 
b has the same birthday as b 

代码:

var people = { 
    a: { 
     name: "a", 
     birthday: 1, 
    }, 
    b: { 
     name: "b", 
     birthday: 2, 
    } 
}; 


for(var x in people) { 
    console.log(people[x].name + " was born on day " + people[x].birthday) 
    for(var y in people) { 
     if(people[x].birthday = people[y].birthday) { 
      console.log(people[x].name + " has the same birthday as " + people[y].name) 
     } 
    } 
} 

people[x].birthday = people[y].birthday 

似乎是问题的根源。

+0

您可以使用人[X] .birthday ===人[Y] .birthday –

回答

5
people[x].birthday == people[y].birthday 

你需要==,而不是==是分配,==是比较

使用=,你要分配people[y].birthdaypeople[x].birthday值,然后两个生日是相同的。

使用==,你会被比较,如果y是同一天生日的x

+0

谢谢,我是个白痴。我有一段时间没有用过JS。 –

3

你只需要使用Identity /全等运算符===两个对象在JavaScript中比较,这样你就可以这样做:

people[x].birthday === people[y].birthday 

看看Comparison operators

注:

people[x].birthday = people[y].birthday永远是true因为在这里你正在做的一项任务。这里

2

两个问题:

  1. 你看起来比较像让渡,而不是平等的检查

people[x].birthday = people[y].birthday

应该是:

people[x].birthday === people[y].birthday 
  • 第二个是在你的for循环中。您从相同索引(0)开始循环两次收集。
  • 最简单的方法是只比较当前与人列表中的每个人是

    for(var index = 0; index < people.length; index++) { 
        console.log(people[x].name + " was born on day " + people[x].birthday) 
        for(var inner = index; inner < people.length; inner+1) { 
         if(people[index].birthday == people[inner].birthday) { 
          console.log(people[index].name + " has the same birthday as " + people[inner].name) 
         } 
        } 
    }