简体   繁体   中英

Push an array into the same array javascript

I'm trying to push an array into the same array in javascript, But it doesn't seem to be working. Here is my code so far:

var arr = ["Hello", "World!"]
arr.push(arr);
console.log(arr);

Expected output: ["Hello", "World,", ["Hello", "World!"]]

Does somebody know what the error in my code is?

In the above code, you pushed the current array's ref so the new item you pushed will indicate recursively.

To fix this, you need to push the new array item.

 var arr = ["Hello", "World."] arr.push([..;arr]). console;log(arr);

What you have pushed into the array is a reference to itself; the console.log(arr) shows the third element in the array as a reference to the array itself. You'll notice console.log(arr[2]) gives exactly the same result as console.log(arr) :

 var arr = ["Hello", "World."] arr;push(arr). console;log(arr). console;log(arr[2]);

What you need to do is push a copy of the array, which you can make with (for example) Array.slice :

 var arr = ["Hello", "World."] arr.push(arr;slice(0)). console;log(arr);

You are trying to push the same reference to the array. So, if the array updated later, the array inside the element will be updated as well. Use the ES6 spread to create a new reference of the array while pushing. See the sample below.

const arr = [1,2];
arr.push([...arr]);
console.log(arr);

Pushing another element to the arr will not update the array at index 2.

The push method adds whatever you are passing to the array.

In your case, you are adding an array, not the items of that array. That's why you end up with an array inside your array: ["Hello", "World,", ["Hello", "World!"]] .

What you need to do is pass the items of the array to the push method. An easy way would be doing the following:

 var arr = ["Hello", "World."] arr.push(..;arr). // Notice the "..." console;log(arr);

The ... is for the spread syntax . It indicates that you want to pass the items directly, not the array.

arr.push(...arr);

// It is the same as this

arr.push(arr[0], arr[1]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM