我想阅读我的JSON并计算分数和显示总数 这不起作用,任何修改代码的建议。
HTML
<div> <p id="newme"> </p> </div>
JS
var points = {"marks" : [
{"Subject" : csharp, "Score" : 5},
{"Subject" : csharp, "Score" : 7},
{"Subject" : Java, "Score" : 6},
{"Subject" : cpp, "Score" : 9 },
{"Subject" : Java, "Score" : 10},
{"Subject" : Java, "Score" : 4}
]
};
points = JSON.stringify(points);
var Java = "Java";
for (var i=0;i<points.marks.length;i++){
if(points.marks[i].Subject==Java){
var totJava = totJava + points.marks[i].Score;
}
}
document.getElementById("newme").innerHTML= totJava;
答案 0 :(得分:1)
你不能有这样的
"Subject" : csharp, //ERROR
最好用双引号"csharp"
var points = {
"marks": [{
"Subject": "csharp",
"Score": 5
}, {
"Subject": "csharp",
"Score": 7
}, {
"Subject": "Java",
"Score": 6
}, {
"Subject": "cpp",
"Score": 9
}, {
"Subject": "Java",
"Score": 10
}, {
"Subject": "Java",
"Score": 4
}]
};
//points = JSON.stringify(points); //NO NEED TO PARSE THIS
var Java = "Java";
var totJava = 0; // declare globally with default 0 as value
for (var i = 0; i < points.marks.length; i++) {
if (points.marks[i].Subject == Java) {
totJava = totJava + points.marks[i].Score;
}
}
document.getElementById("newme").innerHTML = totJava;
答案 1 :(得分:1)
首先它不是一个有效的JSon简单的javascript对象 其次,您应该提供默认总数
var Java = "Java";
var totJava = 0;
for (var i=0;i<points.marks.length;i++){
if(points.marks[i].Subject==Java){
totJava += parseInt(points.marks[i].Score,10);
}
}
document.getElementById("newme").innerHTML= totJava;
答案 2 :(得分:1)
这里有几点不对,请查看http://jsfiddle.net/XQymX/
更新的小提琴json对象就像这样
var points = {"marks" : [{
"Subject" : "csharp",
"Score" : 5
},{
"Subject" : "csharp",
"Score" : 7
},{
"Subject" : "Java",
"Score" : 6
},{
"Subject" : "cpp",
"Score" : 9
},{
"Subject" : "Java",
"Score" : 10
},{
"Subject" : "Java",
"Score" : 4
}
]
};
并且无需执行此操作points = JSON.stringify(points);