12

In Ruby, it's possible for an array to contain itself, making it a recursive array. Is it possible to put a JavaScript array inside itself as well?

var arr = new Array();
arr[0] = "The next element of this array is the array itself."

Now how can I move arr into arr[1] so that the array contains itself recursively, (e. g., so that arr[1] is arr, arr[1][1] contains arr, arr[1][1][1] contains arr, etc.)?

Community
  • 1
  • 1
Anderson Green
  • 30,230
  • 67
  • 195
  • 328

2 Answers2

16

Sure:

var a = [1];
a.push(a);

They're the same object:

a[1] === a[1][1]  // true

And a convincing screenshot:

enter image description here

Blender
  • 289,723
  • 53
  • 439
  • 496
11

Yes, sure:

var x = [];
x.push(x);
console.log(x[0] === x); // true
phihag
  • 278,196
  • 72
  • 453
  • 469