我有一个看起来像这样的数组
var x = [
{
"name" : "Paris",
"count" : [1,30, 20]
},{
"name" : "London",
"count" : [5,30, 10]
}
]
我试图通过添加属性的数字来解决这个问题" count"
var y = [
{
"name" : "Paris",
"count" : 51
},{
"name" : "London",
"count" : 45
}
]
这是我的代码
var y = []
function doTotal(x, i){
var out = 0;
for(var j = 0; j < x[i].count.length; j++){
out += x[i].count[j];
}
}
for(var i = 0; i < x.length; i++){
y[i] = {
name : x[i].name,
total : doTotal(x, i)
}
}
console.log(y)
..总数未定义。我做错了什么?
答案 0 :(得分:2)
您需要在out
函数
dototal
var x = [
{
"name" : "Paris",
"count" : [1,30, 20]
},{
"name" : "London",
"count" : [5,30, 10]
}
]
var y = [
{
"name" : "Paris",
"count" : 51
},{
"name" : "London",
"count" : 45
}
]
function doTotal(x, i){
var out = 0;
for(var j = 0; j < x[i].count.length; j++){
out += x[i].count[j];
}
return out;
}
for(var i = 0; i < x.length; i++){
y[i] = {
name : x[i].name,
total : doTotal(x, i)
}
}
alert(JSON.stringify(y));
&#13;