javascript - Creating new variable from another -


what best way create new array or object another. since doing

 var oldvar = {x:1,y:2} //or [x,y]  var newvar = oldvar 

will link them, bets best way clone or cope new variable?

numbers in javascript

numbers in javascript spec calls 'primitive value type'

from specification numbers:

number value # Ⓣ
primitive value corresponding double-precision 64-bit binary format ieee 754 value.

note number value member of number type , direct representation of number.

so in case newvar copy of oldvar , not reference.

in javascript, number, boolean, undefined, null or string value types. when passing of these 5 around, in fact passing values , not references, no need clone those.

when pass else around (objects) need use cloning since reference types.

when cloning objects in javascript there 2 approaches.

shallow cloning

this means clone 1 level deep. assuming our properties in object enumerable (this case if haven't used property descriptors) can use like:

var = {a:3,b:5};  var copy = {}; for(var prop in a){   copy[prop] = a[prop]; } 

however, want copy object's own properties , not might inherit prototype, can do:

var copy = {}; for(var prop in a){   if(a.hasownproperty(prop)){//check cloned property belongs _a_      copy[prop] = a[prop];   } } 

note these 2 shallow copy properties off a, not deal setting prototype, , clone properties reference (except properties primitive value types :) ).

deep copying

deep copying means creating clone of object several levels deep. calls recursion since deep copying defined such (in psuedocode)

copyobject(object)     if object primitive value type        return object     clone := empty object     every member of object          add copyobject(member) property clone      return clone 

we applying algorithm recursively on object properties of clone.

here sample implementation documented you. assumes es5 (chrome) can adapt other/older browsers. more stuff treat date , regex special cases. keeps dictionary of properties handled able handle circular references in object. intended learning , not production use :) if have questions feel free.

var clone = function (a) {     var passedrefs = [];     // keep track of references passed avoid cycles     var passedrefcreated = [];     function clone2(a1) { // inner function handle 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 object references avoid circular references later         if (a1 instanceof date) { // handle date , regexp 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 array.isarray work. fizzytea catching this.             obj = [];         } else { // create new object prototype of 1 we're cloning support prototypical inheritance. prototypes _shared_             obj = object.create(object.getprototypeof(a1));         }         passedrefcreated[passedrefs.indexof(a1)] = obj; // add references created dict         object.getownpropertynames(a1).foreach(function (prop) { // go through property, ones not enumerable             obj[prop] = clone2(a1[prop]); // call algorithm recursively, in pseudo code above         });         return obj;     }     return clone2(a); // call inner function has access dictionary  } 

(for example, can use for... in loop iterate through properties).


Comments

Popular posts from this blog

Perl - how to grep a block of text from a file -

delphi - How to remove all the grips on a coolbar if I have several coolbands? -

javascript - Animating array of divs; only the final element is modified -