您好,我正在尝试对 3 个 json 对象中的值求和。
var things = {
"noun": {
"syn": ["belongings", "holding", "stuff", "property"]
}
};
var stuff = {
"noun": {
"syn": ["belongings", "holding", "property"]
}
};
var crap = {
"noun": {
"syn": ["things", "holding", "waste"]
}
};
result = {};
word1 = things.noun.syn
for (key in word1) {
nk = word1[key];
if (result.nk == undefined) {
result.nk = 1
} else {
result.nk = result.nk + 1;
}
}
console.log(result);
例如,我得到的结果是 result.nk
而不是 result.belongings
。
我一直在 jsfiddle 中胡闹:http://jsfiddle.net/qunUz/2/
如何计算每个值出现的次数?
最佳答案
要访问给定字符串值的属性,您应该使用括号表示法
result[nk] //access the property defined by nk's value
而不是你正在使用的点符号
result.nk //access the 'nk' property
result['nk'] //equivalent in bracket notation.
关于3 个对象中的 Javascript 求和值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10200566/