比较同一对象中的值

时间:2015-09-04 15:48:05

标签: javascript

所以我正在尝试编写一些代码来检查两个人是否共享同一个生日。你可以看到人“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

似乎是问题的根源。

4 个答案:

答案 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)

您可以使用===。这意味着:等值和相等的类型

详情请见:http://www.w3schools.com/js/js_comparisons.asp

此致

答案 3 :(得分:2)

这里有两个问题:

  1. 您的比较看起来像是作业而不是相等检查
  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)
            }
        }
    }
    
    1. 第二个是你的for循环。从同一索引(0)开始循环遍历集合两次。
    2. 最简单的方法是将当前人与列表中的每个人进行比较

      QGraphicsEllipseItem