4

Recently i was experimenting with array push() method in javascript. I created an array, and pushed the same array using push method.

var a=['hello', 4]

a.push(a)

the result was surprising, when i explored the array items in chrome console, there was infinite array produced. i want to know why this is happening. As the push() method adds the element on last.

I was expecting this result

['hello, 4, ['hello',4]]

but the result was something else, here is the screenshot of chrome console problem screenshot, infinite inner arrays using push method in JavaScript

4

1 回答 1

5

当您将对象分配给 Javascript(实际上是在大多数类似语言中)中的变量时,该变量会保存对该对象的所谓“引用”。请注意,JS 中的数组是对象,但字符串和数字等原始值不是。

对象分配是“通过引用”的一个结果是,您对该对象所做的任何更改——即使它对碰巧引用同一对象的另一个变量所做的更改——将在您检查原始变量时“显示”。

所以在这里,你开始

var a=['hello', 4]

然后做

a.push(a)

然后是a点已更改的对象(数组)。现在它的末尾多了一个元素——也就是a我们正在讨论的同一个数组。

所以它递归地展开:

a = ['hello', 4, a]
  = ['hello', 4, ['hello', 4, a]]
  = ['hello', 4, ['hello', 4, ['hello', 4, a]]]
   ...

以此类推,无穷无尽。这不需要无限量的内存,因为数组的第三个元素只是对保存数组的内存位置的引用。

于 2020-01-21T18:41:26.163 回答