ily*_*lyo 4 javascript variables
从另一个创建新数组或对象的最佳方法是什么.自从做
var oldvar = {x:1,y:2} //or [x,y]
var newvar = oldvar
Run Code Online (Sandbox Code Playgroud)
将链接他们,什么是最好的克隆或处理新变量的方法?
Ben*_*aum 10
JavaScript中的数字是规范称为" 原始值类型 "的数字
数值#Ⓣ
原始值对应于双精度64位二进制格式IEEE 754值.注意Number值是Number类型的成员,是数字的直接表示.
所以在你的情况下newvar将是oldvar 的副本而不是引用.
在JavaScript中Number,Boolean,undefined,null或者String是值类型.当传递这些中的任何一个时,你实际上是传递值而不是引用,不需要克隆它们.
当您传递任何其他内容(对象)时,需要使用克隆,因为它们是引用类型.
在JavaScript中克隆对象时,有两种方法.
这意味着您可以克隆1级深度.假设对象中的所有属性都是可枚举的(如果您没有使用属性描述符,通常就是这种情况),您可以使用以下内容:
var a = {a:3,b:5};
var copy = {};
for(var prop in a){
copy[prop] = a[prop];
}
Run Code Online (Sandbox Code Playgroud)
但是,我们通常希望复制对象自己的属性,而不是它可能从其原型继承的所有内容,因此我们可以这样做:
var copy = {};
for(var prop in a){
if(a.hasOwnProperty(prop)){//check that the cloned property belongs to _a_ itself
copy[prop] = a[prop];
}
}
Run Code Online (Sandbox Code Playgroud)
注意这两个只有浅拷贝属性a,它们不处理设置原型,并通过引用克隆所有属性(除了原始值类型本身的属性:)).
深度复制意味着创建一个深层次的对象的克隆.这会调用递归,因为深度复制是这样定义的(在伪代码中)
CopyObject(object)
If object is a primitive value type
return object
clone := Empty Object
For every member of object
Add CopyObject(member) as a property to clone
Return clone
Run Code Online (Sandbox Code Playgroud)
我们以递归方式将算法应用于克隆的对象属性.
以下是我为您记录的示例实现.它假设ES5(Chrome),但您可以轻松地将其适应其他/旧版浏览器.它做了更多的东西,如治疗Date和Regex特殊情况.它还保存已经处理的属性字典,以便能够处理对象中的循环引用.它用于学习而不是用于生产:)如果您对此有任何疑问,请随意.
var clone = function (a) {
var passedRefs = []; // Keep track of references you passed to avoid cycles
var passedRefCreated = [];
function clone2(a1) { // Inner function to handle the actual cloning
var obj;
if (typeof a1 !== "object" || a1 === null) { // Handle value type
return a1;
}
var locInpPassed = passedRefs.indexOf(a1); // Detect circular reference
if (locInpPassed !== -1) {
return passedRefCreated[locInpPassed];
}
passedRefs.push(a1); // Add the object to the references to avoid circular references later
if (a1 instanceof Date) { // Handle date and RegExp for special cases
obj = new Date(a1.getTime());
} else if (a1 instanceof RegExp) {
obj = new RegExp(a1);
}else if (Array.isArray(a1)){// handle arrays in order for Array.isArray to work. Thanks FizzyTea for catching this.
obj = [];
} else { // Create a new object with the prototype of the one we're cloning to support prototypical inheritance. Prototypes are _shared_
obj = Object.create(Object.getPrototypeOf(a1));
}
passedRefCreated[passedRefs.indexOf(a1)] = obj; // Add to the references created dict
Object.getOwnPropertyNames(a1).forEach(function (prop) { // Go through all the property, even the ones that are not enumerable
obj[prop] = clone2(a1[prop]); // Call the algorithm recursively, just like in the pseudo code above
});
return obj;
}
return clone2(a); // Call the inner function that has access to the dictionary
}
Run Code Online (Sandbox Code Playgroud)
(例如,您可以使用for... in循环来遍历属性).