1

first sorry for my english

I have 2 list or 2 dic, When i write

list1 = list2

list1 become list2 and any change in list1 set in list2

How i can tranfer items from list1 to list2( without using for ) , is there any way ?

RobG
  • 142,382
  • 31
  • 172
  • 209
  • 3
    list1=list2.slice(); will make a new array. changes to objects in the array will still cross-populate... – dandavis Dec 03 '14 at 08:25
  • This question has been asked many, many times before. Copying an array is trivial, but there is no single or general way to copy an object as there are different requirements for different types of object. The duplicate has many answers, read quite a few as no single answer has the full story. – RobG Dec 03 '14 at 08:34
  • sorry , i have bad english and i dont know what must i google ! – user3892518 Dec 03 '14 at 08:40

2 Answers2

1

Use slice to create a copy of the array:

list1 = list2.slice()
k-nut
  • 3,447
  • 2
  • 18
  • 28
1

Pure javascript, do a copy

for(i=0;i<list2.length;i++) {
  list1[i] = list2[i];
}

There are also shallow-clone and deep-clone copy methods in jquery and lodash/underscore. But why not just slice it?

list1 = list2.slice();
deitch
  • 14,019
  • 14
  • 68
  • 96
  • The for loop will create properties on *list1* that don't exist on *list2* if *list2* is sparse. – RobG Dec 03 '14 at 08:39
  • @RobG yeah, true, but I think the basic question is there. In any case, `slice` (I typed that as "splice" at first since the p is near the l; big difference!) is easier. – deitch Dec 03 '14 at 09:01
  • I think the OP is asking about arrays ("list") and objects ("dic"). But not certain about that… – RobG Dec 03 '14 at 09:30
  • Huh, good point there. – deitch Dec 03 '14 at 09:39