2015-09-04 77 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) 
         } 
        } 
    }