arrays - Javascript unbind variables -
this question has answer here:
- how correctly clone javascript object? 51 answers
i have following code copy variable value change value.
var = [{name: 'john doe'}]; var b = a; document.write(b[0].name + '<br />'); document.write(a[0].name + '<br /><br />'); b[0].name = 'jane doe'; document.write(b[0].name + '<br />'); document.write(a[0].name + '<br />');
but somehow change first variable value
how make variable keep value?
you assigning a
-reference b
. may want copying array changes a
not reflected b
. see this thread different assignments in javascript.
take @ fastest way duplicate array. it's speed of different array copy methods. quick answer is:
var b = a.slice();
the slice()
method creates new array same elements original one. careful it's shallow copy.
you use json.stringify()
, json.parse()
methods doing deep copy.