开发者

Totally basic Javascript reference question

开发者 https://www.devze.com 2022-12-09 02:03 出处:网络
The following in a Javascript console: var a = {\'foo\': []}; var b = {}; for (var key in a) { b[key] = a[key];

The following in a Javascript console:

var a = {'foo': []};
var b = {};

for (var key in a) {
   b[key] = a[key];
}

a['foo'].push(1);

console.log(b);

Yields:

Object foo=[1]

I want to make a copy by value in b of each array for each开发者_JS百科 key in a. Is there an easier way?


You could make a "clone" function that creates a new object, based on the original object constructor, and then clone that original object properties also if they are objects:

function clone(obj){
  if(typeof(obj) != 'object' && obj != null) 
    return obj; // return the value itself if isn't an object
                // or null, since typeof  null == 'object';

    var temp = new obj.constructor();

    for(var key in obj)
        temp[key] = clone(obj[key]);
    return temp;
}


var a = {'foo': []};
var b = clone(a);

a['foo'].push(1);

console.log(b); // Object foo=[0]


This is called Deep Copy. You can find examples in:

  • http://www.overset.com/2007/07/11/javascript-recursive-object-copy-deep-object-copy-pass-by-value/
  • (Deep) copying an array using jQuery


Easier way:

var a = {'foo': []};
var b = a;

a['foo'].push(1);

console.log(b);

Output is the same.

Edit:

var a = {'foo': []};
var b = {};

for (var key in a) {
    if (a.hasOwnProperty(key)) {
        b[key] = [];
        for (var i = 0; i < a[key].length; i += 1) {
            b[key][i] = a[key][i];
        }
    }
}

a['foo'].push(1);

console.log(b);


As this will add support for deep-copying arrays in your code:

var a = {'foo': []};
var b = {};

for (var key in a) {
   if (Object.prototype.toString.call(b[key]) === "[object Array]") {
      b[key] = a[key].slice(0);
   } else {
      b[key] = a[key];
   }
}

a['foo'].push(1);

console.log(b);
0

精彩评论

暂无评论...
验证码 换一张
取 消