我正在尝试将变量venueID 存储的字符串添加到名为“stop”的对象中。停靠点对象存储在称为 field 的对象中。出于某种原因,如果 field 对象中尚不存在特定站点,则当我将站点添加到 field 对象并将其设置为等于具有属性venueID的另一个对象时, field ID将添加为字符串“venueID”而不是存储在变量venueID 中的值。为什么是这样?
var getMostPopularVenues = function(checkins) {
var venues = {};
for (var i = 0; i < checkins.length; i++) {
var checkin = checkins[i];
var venue = {'venueName' : checkin['venueName'], 'count' : 1};
var stop = checkin['stop'];
var venueID = checkin['venueID'];
if (stop in venues) {
if (venueID in venues[stop]) {
venues[stop][venueID]['count']++;
}
else {
venues[stop][venueID] = venue;
}
}
else {
console.log(venueID); // correctly prints the actual venueID that I want to set as the property
venues[stop] = {venueID : venue}; // this line gives the stop a property called the string 'venueID' instead of the value stored by the variable venueID
}
}
最佳答案
对象字面量 {venueID :venue}
与 {"venueID":venue}
相同。
对象文字不能用于设置动态属性名称,并且必须分两部分完成。
例如,
venues[stop] = {};
venues[stop][venueID] = venue;
关于javascript - 为什么将变量作为属性添加到循环中的对象时,第一次会添加变量的实际名称作为属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21397802/