单击按钮时,我希望列出数组中的结果,例如:John Smith 16,Jack Snow 10等。
我想使用一个循环但是我的循环中的代码现在是不正确的,因为当我单击按钮时,我得到的是:[object Object]。
有人可以提供可能的解决方法吗?
function begin() {
listresults();
();
}
var results1 = {name:"John Smith", score:16};
var results2 = {name:"Jack Sow", score:10};
var results3 = {name:"Tessa Flip", score:15};
var results = [results1, results2, results3];
function listresults() {
var text = "";
var total = 0;
var i;
for (i in results) {
text += results[i] + "<br>";
}
document.getElementById('message').innerHTML = text;
}
答案 0 :(得分:1)
我首先检查两个数组的长度是否相同。然后使用for循环迭代:
final int timeLength = TIME.length;
if (timeLength != stat.size()) {
//something may not be right
}
for (int i = 0; i < timeLength; i++) {
System.out.println(time[i]+" "+stat.get(i));
}
答案 1 :(得分:0)
当您在字段中追加对象而不是对象值时。
这是从对象访问名称和分数的正确方法,当您循环遍历对象数组时返回该对象:
function begin() {
listresults();
();
}
var results1 = {name:"John Smith", score:16};
var results2 = {name:"Jack Sow", score:10};
var results3 = {name:"Tessa Flip", score:15};
var results = [results1, results2, results3];
function listresults() {
var text = "";
var total = 0;
for (var i=0; i < results.length; i++) {
text += results[i].name + " " + results[i].score + "<br>";
}
document.getElementById('message').innerHTML = text;
}
答案 2 :(得分:0)
建议您使用Array
方法(map,join)而不是纯循环
function begin() {
listresults();
}
var results1 = {name:"John Smith", score:16};
var results2 = {name:"Jack Sow", score:10};
var results3 = {name:"Tessa Flip", score:15};
var results = [results1, results2, results3];
function listresults() {
document.getElementById('message').innerHTML =
results.map(function(item) {
return item.name + ' ' + item.score;
}).join('<br>');
document.getElementById('total').innerHTML =
results.map(function(item) {
return item.score;
}).reduce(function(sum, score) {
return sum + score;
}, 0);
}
<button onclick="begin()">begin</button>
<br />
<div id="message"></div>
<div>total: <span id="total">0</span></div>
答案 3 :(得分:0)
您正在数组results1, results2,
中推送对象'results'
等。
因此,在迭代数组时,您应该访问对象属性,如下所示:
function listresults() {
var text = "";
var total = 0;
var i;
for (i in results) {
text += results[i]['name'] + ' ' + results[i]['score'] + "<br>";
}
答案 4 :(得分:0)
var results1 = {name:"John Smith", score:16};
var results2 = {name:"Jack Sow", score:10};
var results3 = {name:"Tessa Flip", score:15};
var results = [results1, results2, results3];
var res = results.map(item => { return item.name+ " " +item.score });
console.log(res.join(", "));
&#13;