Javascript Object Addition Assignment Operator -
i trying use addition assignment operator within javascript object in order add number of votes in student election. given following:
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" } };
i trying preform for/in loop in order count , create new object names of candidates , number of votes have:
var president = {}; (var student in votes) { president[votes[student].president] += 1; };
which, know, gives me nan values.
how key of property increase each iteration?
the problem not initializing value. first time encounter name, have president[votes[student].president]
undefined, undefined + 1
give nan
, thereafter each addition give nan
since nan + 1
nan
var president = {}, president; (var student in votes) { president = votes[student].president; if (!president[president]) { president[president] = 0; } president[president] += 1; };