所以我正在尝试编写一些代码来检查两个人是否共享同一个生日。你可以看到人“a”和人“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 :(得分:5)
people[x].birthday == people[y].birthday
您需要==
而不是=
。 =
是作业,==
是比较
使用=
,您将people[y].birthday
值分配给people[x].birthday
值,然后两个生日相同。
使用==
,您将比较y
是否与x
生日相同
答案 1 :(得分:3)
您只需要使用Identity / strict相等运算符===
来比较JavaScript中的两个对象,这样就可以:
people[x].birthday === people[y].birthday
查看 Comparison operators 。
注意:强>
people[x].birthday = people[y].birthday
始终为true
,因为您正在执行作业。
答案 2 :(得分:2)
答案 3 :(得分:2)
这里有两个问题:
people[x].birthday === people[y].birthday
应该是:
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)
}
}
}
最简单的方法是将当前人与列表中的每个人进行比较
QGraphicsEllipseItem