Totally basic Javascript reference question
A:在控制台下面的JavaScript
1 2 3 4 5 6 7 8 9 10 | var a = {'foo': []}; var b = {}; for (var key in a) { b[key] = a[key]; } a['foo'].push(1); console.log(b); |
收益:
我想做一个拷贝的值在每个阵列中的每个密钥B在A中有更容易的方法吗?
您可以创建一个"clone"函数,该函数基于原始对象构造函数创建一个新对象,然后克隆原始对象属性(如果它们是对象):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | 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] |
这被称为深度复制。您可以在以下位置找到示例:
- http://www.overset.com/2007/07/11/javascript-recursive-object-copy-deep-object-copy-pass-by-value/
- (深)使用jquery复制数组
因为这将增加对代码中深度复制数组的支持:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | 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); |
更简单的方法:
1 2 3 4 5 6 | var a = {'foo': []}; var b = a; a['foo'].push(1); console.log(b); |
输出相同。
编辑:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | 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); |