-1

some times in typescript when i pass a variable as a parameter in a function and modify it in the function the original variable also modify can any one explain to me what's happening

let mybrew :any[] = [
    {
        id:5,
        materials:[-1,-1,-1,-1],
        price:16
        },

]
console.log(mybrew);
function bestBrew(abrow:any[]){
    abrow.forEach(
        e=>{
            for (let i = 0; i < e.materials.length; i++) {
            e.materials[0] += e.materials[i];
            }
        }
    )
}
bestBrew(mybrew);
console.log(mybrew);

output

[ { id: 5, materials: [ -1, -1, -1, -1 ], price: 16 } ]
[ { id: 5, materials: [ -5, -1, -1, -1 ], price: 16 } ]

1 Answers1

1

You can do some deep clone on the object.

lent newbrew = JSON.parse(JSON.stringify(mybrew));
bestBrew(newbrew);

York Chen
  • 744
  • 4
  • 9