我无法理解为什么只显示这个多维数组的最后一行。这是server.js
中的数组:
var ar = Array(4);
for(var i=0;i<ar.length;i++){
ar[i]=Array(4);
}
ar[0][0]='1';
ar[0][1]='2';
ar[0][2]="3";
ar[0][3]="4";
ar[1][0]='5';
ar[1][1]='6';
ar[1][2]="7";
ar[1][3]="8";
ar[2][0]="9";
ar[2][1]="10";
ar[2][2]="11";
ar[2][3]="12";
ar[3][0]="13";
ar[3][1]="14";
ar[3][2]="15";
ar[3][3]="16"
然后当我在client.js
中迭代数组时,这样:
for(var i = 0; i < scores.length; i++){
console.log(scores[i]);
var someScores = scores[i];
}
document.getElementById('display').innerHTML = someScores;
它只显示13,14,15,16
答案 0 :(得分:2)
你正在每个循环覆盖变量
someScores = scores[i];
你需要像
这样的东西someScores += scores[i] + ' ';
并使用
进行声明和初始化(在循环外部)var someScores = '';
工作示例:
var scores = [['1', '2', "3", "4"], ['5', '6', "7", "8"], ["9", "10", "11", "12"], ["13", "14", "15", "16"]],
i,
someScores = '';
for (var i = 0; i < scores.length; i++) {
someScores += scores[i] + '<br>';
}
document.getElementById('display').innerHTML = someScores;
document.getElementById('display2').innerHTML = scores.join('<br>'); // faster
&#13;
<div id="display"></div><hr />
<div id="display2"></div>
&#13;
答案 1 :(得分:1)
您可以这样做,定义somescores
,并.map
将值添加到somescores
var ar = [
['1', '2', "3", "4"],
['5', '6', "7", "8"],
["9", "10", "11", "12"],
["13", "14", "15", "16"]
];
var someScores = '';
ar.map(function(i) {
someScores += i + '<br>';
});
document.getElementById('display').innerHTML = someScores;
<div id="display"></div>