duplicating arrays javascript splicing

▼魔方 西西 提交于 2019-12-06 06:14:50

Use array1.concat() to duplicate the array instead of passing a reference to array1:

var array1 = [0,1,2,3,4,5];
var array2 = array1.concat();
array2.splice(1,0,1) //add  
console.log(array1);
console.log(array2);

array.concat() can concatenate multiple arrays, but if you pass an empty argument, you're effectively concatenating an array with nothing: cloning the array.

Note that any array and object elements are still references:

var a = [ [1], 2];
var b = a.concat();
b[0][0] = 0;
console.log(b); // gives 0,2
console.log(c); // gives 0,2 too!

If you are using jQuery you can do:

var array1 = [0,1,2,3,4,5];
var array2 = array1.slice();
array2.splice(1,0,1) //add  
console.log(array1);
console.log(array2);

Check out this example.

Arrays and objects are copied by reference. Try this:

Object.prototype.clone = function() {
  var newObj = (this instanceof Array) ? [] : {};
  for (i in this) {
    if (i == 'clone') continue;
    if (this[i] && typeof this[i] == "object") {
      newObj[i] = this[i].clone();
    } else newObj[i] = this[i]
  } return newObj;
}

var array1 = [0,1,2,3,4,5];
var array2 = array1.clone();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!