我的fill()
函数应该用width
仅用零填充height
的二维数组。这是一个带有以下代码块的fiddle。
var row = new Array(),
graph = new Array();
var width = 10, height = 10;
function fill(){
for (var i = 0; i < height; i++){
for (var k = 0; k < width; k++)
row[k] = 0;
graph[i] = row;
}
//as expected, it will log 10 arrays, each of 10 zeros
console.log(graph);
//should set the 2nd element of the 2nd array to "why?"
graph[1][1] = "why?";
//instead, it sets every 2nd element of every array to "why?"
console.log(graph);
}
fill();
我甚至尝试使用以下时髦的代码行制作我的2D数组:
var graph = Array.apply(null, new Array(height)).map(Array.prototype.valueOf,
Array.apply(null, new Array(width)).map(Number.prototype.valueOf,0));
但是,graph[1][1] = "why?"
仍会导致graph
内每个数组的第二个元素设置为"why"?
。为什么?我不允许在JavaScript中填充这样的数组吗?
答案 0 :(得分:2)
因为您已经在图表中填充了10行对一行的引用。
解决这个问题只是这样做:
function fill(){
for (var i = 0; i < height; i++){
var row = new Array();
for (var k = 0; k < width; k++) {
row[k] = 0;
}
graph[i] = row;
}
答案 1 :(得分:1)
这是因为您的row
数组是引用,所有graph
元素都指向同一个引用
尝试类似下面的内容
function fill(width, height){ // pass width and height as parameters
var graph = []; // use [] instead of new Array()
for (var i = 0; i < height; i++){
var row = [];
for (var k = 0; k < width; k++)
row[k] = 0;
graph[i] = row;
}
console.log(graph); // prints the original array
graph[1][1] = "why?"; // set the 2nd element of the 2nd array to "why?"
console.log(graph); // re-print
return graph;
}
fill(10,10);
答案 2 :(得分:1)
<强>解决方案:强>
var row = new Array(), graph = new Array();
var width = 10, height = 10;
function fill(){
for (var i = 0; i < height; i++){
for (var k = 0; k < width; k++){row[k] = 0;}
graph[i] = row.slice(0);
}
console.log(graph);
graph[1][1] = "why?";
console.log(graph);
}
fill();
问题:
您的代码创建了对另一个数组(graph
)的引用数组(row
)。您不希望graph
包含对row
的引用,而是希望graph
包含row
的克隆。上面的代码解决了这个问题。
答案 3 :(得分:0)
因为您只创建了一行(数组)并将相同的数组分配给每个网格位置。