Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible for a JavaScript array to contain itself?

Tags:

javascript

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.)?

like image 651
Anderson Green Avatar asked May 21 '13 19:05

Anderson Green


People also ask

What can an array contains in JavaScript?

Array contains a primitive value A primitive value in JavaScript is a string, number, boolean, symbol, and special value undefined . const hasValue = array. includes(value[, fromIndex]);

Can JavaScript arrays contain objects?

There are various methods to check an array includes an object or not. Using includes() Method: If array contains an object/element can be determined by using includes() method. This method returns true if the array contains the object/element else return false.

Can we store array inside array in JavaScript?

JavaScript does not provide the multidimensional array natively. However, you can create a multidimensional array by defining an array of elements, where each element is also another array. For this reason, we can say that a JavaScript multidimensional array is an array of arrays.

Can arrays contain variables JavaScript?

JavaScript variables can be objects. Arrays are special kinds of objects. Because of this, you can have variables of different types in the same Array.


1 Answers

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

like image 131
Blender Avatar answered Oct 23 '22 16:10

Blender