arrays - Freeze variable value in javascript -



arrays - Freeze variable value in javascript -

i'm having issue saving variable value @ time in javascript. @ basic level, in code below, variable 'b' maintain value assigned

var = []; var b = ''; var c = 'value'; a.push(c); b = a; console.log(b); // b = ["value"] a.push(c); console.log(b); // b = ["value", "value"], want ["value"]

i've seen various solutions similar problems using closures such in question: intentionally "freezing" javascript variable using self-executing function. have tried solution unsuccessfully in jsbin: http://jsbin.com/zusara/1/edit?js,console.

any help appreciated. , best!

assigning array variable not create copy. both a , b variables point same array , alter made via either variable show in other.

if want re-create of array in javascript, have explicitly create re-create of array.

var = []; var c = 'value'; a.push(c); // create shallow re-create of b var b = a.slice(0);

b contains separate array , modifications of a not impact b.

note: shallow copy, not deep re-create , solution arrays. shallow re-create doesn't not re-create objects in array or objects in objects. making deep re-create requires substantially more code, not required , not appear required in case illustration provided.

if want deep re-create , want include objects too, not arrays (i provided simple solution shallow re-create of array), can see reference there plenty of options , debate here:

what efficient way clone object?

javascript arrays closures

Comments

Popular posts from this blog

xslt - DocBook 5 to PDF transform failing with error: "fo:flow" is missing child elements. Required content model: marker* -

mediawiki - How do I insert tables inside infoboxes on Wikia pages? -

Local Service User Logged into Windows -