所以我試圖編寫一些代碼來檢查兩個人是否共享相同的生日。正如你所看到的人「一個」和個人「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
似乎是問題的根源。
您可以使用人[X] .birthday ===人[Y] .birthday –