Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/415.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 导致问题的新数组()中的指针_Javascript_Arrays_Pointers - Fatal编程技术网

Javascript 导致问题的新数组()中的指针

Javascript 导致问题的新数组()中的指针,javascript,arrays,pointers,Javascript,Arrays,Pointers,有人能给我解释一下,为什么使用新的数组并用更多的数组填充它?一个以相同方式生成的矩阵,会导致最后只有一个引用 例如,如果创建一个5x4的矩阵并用零填充它 var matrix = new Array(5).fill( new Array(3).fill(0) ) // 0 0 0 // 0 0 0 // 0 0 0 // 0 0 0 // 0 0 0 如果更改一个元素,它会影响整行,为什么 matrix[3][1] = 5 //This is what I get // 0

有人能给我解释一下,为什么使用新的数组并用更多的数组填充它?一个以相同方式生成的矩阵,会导致最后只有一个引用

例如,如果创建一个5x4的矩阵并用零填充它

var matrix = new Array(5).fill( new Array(3).fill(0) )
// 0  0  0
// 0  0  0
// 0  0  0
// 0  0  0
// 0  0  0
如果更改一个元素,它会影响整行,为什么

matrix[3][1] = 5
//This is what I get
// 0  5  0 
// 0  5  0
// 0  5  0
// 0  5  0
// 0  5  0
片段

var矩阵=新阵列5.fill新阵列3.fill0 console.logmatrix之前。。。 matrix.forEachrow=>console.logrow 矩阵[3][1]=5 console.logmatrix在。。。 matrix.forEachrow=>console.logrownewarray3.fill0作为参数计算一次,其返回值一个特定数组复制到外部数组的每个元素中。您需要使用一个循环来调用new Array3.fill0 5次,或者将其放入一个lambda中,该函数将为外部数组的每个元素调用lambda,例如:

Array.from(new Array(5), () => new Array(3).fill(0));

从Keith的注释展开

是,您只创建了一个内部数组实例。要为每行获取多个实例,您可以尝试以下构造->var matrix=new Array5.fill0.map=>new Array3.fill0或array.fromnew Array5,=>new Array3.fill0;