Reputation: 3
I have a constant array items[], i want to copy it to array2[].
how to do it when i do it the item array get printed two times in console.
how to achieve this aim?
window.onload="arr1()"
function arr1()
{
const items = [
{ label: '1:40', url: '1.png' },
{ label: '2:20', url: '2.png' },
{ label: '3:50', url: '3.png' },
{ label: '4:45', url: '4.png' }]
console.log(items);
console.log(arr2);
}
Upvotes: 0
Views: 1478
Reputation: 375
just assign items to arr2 to copy all data of items into arr2 like
var arr2 = items;
Upvotes: 0
Reputation: 380
Try this:
var arr2 = items.slice();
As slice() creates a new array and return it.
Hope it helps!
Upvotes: 0
Reputation: 577
const items = [
{ label: '1:40', url: '1.png' },
{ label: '2:20', url: '2.png' },
{ label: '3:50', url: '3.png' },
{ label: '4:45', url: '4.png' }];
const arr2 = items;
console.log(items);
console.log(arr2);
Upvotes: 2
Reputation: 337
function arr1()
{
const items = [
{ label: '1:40', url: '1.png' },
{ label: '2:20', url: '2.png' },
{ label: '3:50', url: '3.png' },
{ label: '4:45', url: '4.png' }]
console.log(items);
const arr2 = Object.assign([],items)
console.log(arr2);
}
window.onload=arr1()
Im not sure if this is what you are looking for. but there is a function that is called 'onload' and then it creates an array prints it, copies it and then prints it again
Upvotes: 0