You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript循环内重新初始化变量的影响解析——以zeroArray构建二维零数组为例

Why Reinitializing the 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):

  1. First outer loop (i=0): The inner loop pushes two 0s into row, making it [0, 0]. You push this row into newArray—so newArray is now [[0, 0]].
  2. Second outer loop (i=1): Instead of starting fresh, you add two more 0s to the same row, which becomes [0, 0, 0, 0]. When you push row into newArray, you’re not adding a new array—you’re adding another reference to the exact same array in memory. Now newArray is [[0,0,0,0], [0,0,0,0]] (both elements point to the identical array).
  3. Third outer loop (i=2): You add two more 0s to the same row, making it [0,0,0,0,0,0]. Pushing it into newArray adds a third reference to that single array. The final matrix ends 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:

  1. First outer loop (i=0): Create a new empty row, push two 0s to make [0,0], then push this unique array to newArray.
  2. Second outer loop (i=1): Create another fresh empty row, push two 0s to make [0,0], push this separate array to newArray.
  3. Third outer loop (i=2): Create a third new empty row, push two 0s, push it to newArray.

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 22:24:07