简体   繁体   中英

Push from one array to another by reference

Given this fiddle, does anyone have a suggestion as to how I might update the indices of array1? Or more to the point, any idea how to make the indices of array2 references to indices of array1?

http://jsfiddle.net/y8rs56r3/

    var array1 = [
        {num:"one"},
        {num:"two"},    
        {num:"three"}
    ];
    var array2 = [];
    var i = array1.length;
    while(i--){
        if(i!=1)array2.push(array1[i]);
    }

    array2[0].num = "one updated";
    console.log(array2);
    console.log(array1);

Obviously, in this codeblock, array1[0] is not updated.

since your array is set of objects try like this:

  var array1 = [
              {num:"one"},
              {num:"two"},    
              {num:"three"}
          ];
       var array2 = [];
         for(x in array1){
                   array2.push(array1[x]);
                    }
          array2[0].num = "one updated";
          console.log(array2);//output  [Object { num="one updated"}, Object { num="two"}, Object { num="three"}]
          console.log(array1);// output  [Object { num="one updated"}, Object { num="two"}, Object { num="three"}]

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