0

here the src code

let mod_src_0 = "str1";
let mod_src_1 = "str2";
let mod_src_array = [mod_src_0,mod_src_1];
let mod_src_export = [];
 let mod_obj = function(){

    let temp = {};
    for(let mod in mod_src_array){
        temp.id = mod_src_array[mod];

        mod_src_export.push(temp);
    }



    console.log(mod_src_export)


}
mod_obj()

and the result is [ { id: 'str2' }, { id: 'str2' } ] instead of [ { id: 'str1' }, { id: 'str2' } ]

why is this happening? does it have anything to do with the javascript array.push function?

Sqro2
  • 21
  • 1
  • 5
  • You only have one object in memory, `temp`, which you're mutating and pushing to the array, so at the end, you have multiple items in the array that all point to the same location in memory (and so have the same `id` when observed then) – CertainPerformance Mar 12 '19 at 20:55
  • yeah the memory location is same but the contents have been overwritten each time. is not it? – Sqro2 Mar 12 '19 at 21:02
  • The overwriting you're doing is here: `temp.id = mod_src_array[mod];` You're not overwriting `temp` with a new object in memory, you're just *reassigning* the existing `id` property on the existing `temp` object. – CertainPerformance Mar 12 '19 at 21:19

0 Answers0