Home > Net >  How to create a new array with the same content?
How to create a new array with the same content?

Time:10-25

I use an external library to iterate over the array. It has the next() function to go to the next array item and returns false if there is no next item. If the next() is called the first time, then it returns the first item.

But here is how it works -

var a = ['item1'];
a.next(); // 'item1' is returned
...
a = ['item1']; // it could be called several times
a.next(); // false is returned, but 'item1' is expected

Is there any way to make a array to be treated as new array by next() function? I tried to add new elements to a (a.push(' ')) and it works well, but then I have to deal with an empty array elements.

CodePudding user response:

If it's a one dimensional array you could probably do something like:

let newArray = [...oldArray];

This would create a new array.

Can I ask you why you are using an external library to map over an array?

CodePudding user response:

You could use the spread operator to create a shallow copy of that array.

var a = [1,2,3];
var b = [...a];

a.push(4);

console.log("a = "   a);
console.log("b = "   b);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related