我有一个动态数组,如果数组中存在该键,我将尝试将该值递增 1。根据我的调试,它正在递增键并创建第二个键/值对。
我的代码片段:
for (var i = 0; i < choices.length; i++) {
console.log(choices[i]);
if (choices[i].YearTermId == 1) {
if (!lookup(firstChoice, choices[i].FirstChoiceOptionId)) {
firstChoice.push({
key: choices[i].FirstChoiceOptionId,
value: 1
});
} else {
firstChoice[choices[i].FirstChoiceOptionId] = firstChoice[choices[i].FirstChoiceOptionId] + 1;
}
更多如果/否则..
function lookup( arr, name ) {
for(var i = 0, len = arr.length; i < len; i++) {
if( arr[ i ].key === name )
return true;
}
return false;
}
最佳答案
您在本应使用对象的地方使用了数组。如果您使用一个对象,您的代码可以重写为:
var firstChoice = {};
for (var i = 0; i < choices.length; i++) {
var firstChoiceOptionId = choices[i].FirstChoiceOptionId;
if (choices[i].YearTermId == 1) {
firstChoice[firstChoiceOptionId] = firstChoice[firstChoiceOptionId]
? firstChoice[firstChoiceOptionId] + 1
: 1;
/* ... */
}
}
如果之后需要将数据作为数组,只需将其映射即可:
var firstChoiceArray = Object.keys(firstChoice).map(function(key) {
return {
key: key,
value: firstChoice[key]
};
});
相反,如果您有一个输入数组并想将其转换为对象进行操作,则将其归约:
var firstChoice = firstChoiceArray.reduce(function(result, current) {
result[current.key] = current.value;
return result;
}, {});
关于javascript数组 - 在给定键处增加值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36212994/