JavaScript循环内重新初始化变量的影响解析——以zeroArray构建二维零数组为例
row Array Fixes Your 2D Zero Array in JavaScript? Great question—this boils down to a core JavaScript concept: arrays are reference types, not value types. Let’s break this down step by step so it makes total sense.
First, Let’s Unpack the Problem in Your Original Code
Your original code declares let row = []; outside the outer for loop. That means every time you run through the outer loop, you’re working with the exact same array in memory for row. Here’s what happens when you call zeroArray(3, 2):
- First outer loop (i=0): The inner loop pushes two
0s intorow, making it[0, 0]. You push thisrowintonewArray—sonewArrayis now[[0, 0]]. - Second outer loop (i=1): Instead of starting fresh, you add two more
0s to the samerow, which becomes[0, 0, 0, 0]. When you pushrowintonewArray, you’re not adding a new array—you’re adding another reference to the exact same array in memory. NownewArrayis[[0,0,0,0], [0,0,0,0]](both elements point to the identical array). - Third outer loop (i=2): You add two more
0s to the samerow, making it[0,0,0,0,0,0]. Pushing it intonewArrayadds a third reference to that single array. The finalmatrixends up as three copies of the same 6-element array:[[0,0,0,0,0,0], [0,0,0,0,0,0], [0,0,0,0,0,0]].
Why Moving row = [] Inside the Outer Loop Works
When you move let row = []; inside the outer loop, you’re creating a brand new array in memory every time the outer loop runs. Here’s the corrected flow:
- First outer loop (i=0): Create a new empty
row, push two0s to make[0,0], then push this unique array tonewArray. - Second outer loop (i=1): Create another fresh empty
row, push two0s to make[0,0], push this separate array tonewArray. - Third outer loop (i=2): Create a third new empty
row, push two0s, push it tonewArray.
Now newArray holds three distinct array references, each pointing to their own [0,0] array—exactly the [[0,0], [0,0], [0,0]] result you expect.
The Key Takeaway
In JavaScript, when you assign an array to a variable or push it into another array, you’re not copying the array itself—you’re copying a reference (a pointer) to where the array lives in memory. If you reuse the same array reference across loops, every change you make to that array will be reflected everywhere that reference exists. Reinitializing row inside the loop ensures you’re working with a fresh, independent array each time.
内容的提问来源于stack exchange,提问作者Kleva_ Saki

