Strange behavior array in object JavaScript -
why b.first[0] return "t" , how can avoid this?
i need safe "q" in b.first[0]
var extend = function(o,p){ for(prop in p){ o[prop] = p[prop]; } return o; }; var = {first:['q','w']}; var b = {}; extend(b,a); document.write(a.first[0]); //q document.write(b.first[0]); //q a.first[0] = 't'; document.write(a.first[0]); // t document.write(b.first[0]); // t ?????????????????????
this issue relating concept extending b doesn't recreate data a. if of data object (like array), instead "points" array instead of creating new, identical array. you're storing 2 pointers same array, when change one, change other.
here answer discusses idea of "cloning" object in javascript in more detail.
Comments
Post a Comment