Javascript对象加法赋值运算符

时间:2015-04-23 01:03:39

标签: javascript object-literal

我正在尝试在javascript对象中使用附加赋值运算符,以便在学生选举中累加投票数。鉴于以下内容:

var votes = {
  "Alex": { president: "Bob", vicePresident: "Devin", secretary: "Gail", treasurer: "Kerry" },
  "Bob": { president: "Mary", vicePresident: "Hermann", secretary: "Fred", treasurer: "Ivy" },
  "Cindy": { president: "Cindy", vicePresident: "Hermann", secretary: "Bob", treasurer: "Bob" },
  "Devin": { president: "Louise", vicePresident: "John", secretary: "Bob", treasurer: "Fred" },
  "Ernest": { president: "Fred", vicePresident: "Hermann", secretary: "Fred", treasurer: "Ivy" },
  "Fred": { president: "Louise", vicePresident: "Alex", secretary: "Ivy", treasurer: "Ivy" },
  "Gail": { president: "Fred", vicePresident: "Alex", secretary: "Ivy", treasurer: "Bob" },
  "Hermann": { president: "Ivy", vicePresident: "Kerry", secretary: "Fred", treasurer: "Ivy" },
  "Ivy": { president: "Louise", vicePresident: "Hermann", secretary: "Fred", treasurer: "Gail" },
  "John": { president: "Louise", vicePresident: "Hermann", secretary: "Fred", treasurer: "Kerry" },
  "Kerry": { president: "Fred", vicePresident: "Mary", secretary: "Fred", treasurer: "Ivy" }
};

我正在尝试执行for / in循环,以便计算并创建一个新对象,其中包含候选人的姓名和他们拥有的投票数:

var President = {};
for (var student in votes) {
  President[votes[student].president] += 1;
};

正如您可能已经知道的那样,它给了我所有的NaN值。

如何在每次迭代时获得属性的密钥增加?

3 个答案:

答案 0 :(得分:0)

您需要在递增之前使用值初始化President[votes[student].president]。也许有这样的事情:

if(President[votes[student].president]) {
  President[votes[student].president] += 1
} else {
  President[votes[student].president] = 1;
}

答案 1 :(得分:0)

问题是您没有初始化该值。因此,当您第一次遇到名称时,President[votes[student].president]为未定义,因此undefined + 1将为您提供NaN,此后每次添加都会为您提供NaN,因为{{1}是NaN + 1

NaN

答案 2 :(得分:0)

更改此代码,因为您需要初始化变量;)

    var President = {};
    for (var student in votes) {
      if(!President[votes[student].president]){
         President[votes[student].president] = 0; 
      }
      President[votes[student].president] += 1;
    };