I'm sure there is an easy answer for this, though I only really have experience with PHP. Why does the "pizza" array change when I pass it to my function as "my_pizza" and only make changes to "my_pizza"? How do I keep my original array I pass to the function outside of the function? Once the function is finished running, the pizza array should have not changed. I noticed if I change my string variable (pie) it will stay the same after the function runs, unlike the array.
In short, I want the first set of results to be identical to the second.
var pizza = [];
pizza.push('crust');
pizza.push('ham');
var pie = "apple"
function bake_goods(my_pizza, my_pie){
console.log(my_pizza);
console.log(my_pie);
delete my_pizza['1'];
my_pie = "peach";
console.log(my_pizza);
console.log(my_pie);
}
//first run
bake_goods(pizza, pie);
//console logs
//['crust','ham']
//apple
//['crust']
//peach
//second run
bake_goods(pizza, pie);
//console logs
//['crust']
//apple
//['crust']
//peach
you should clone (create a copy of) your array in your function
function bake_goods(my_pizza, my_pie){
var innerPizza = my_pizza.slice(0);
console.log(innerPizza);
console.log(my_pie);
delete innerPizza ['1'];
my_pie = "peach";
console.log(innerPizza );
console.log(my_pie);
}
Arrays and objects are passed as pointers to the original object. If you don't want to modify the original, you need to make a copy first.
function bake_goods(my_pizza, my_pie) {
my_pizza = my_pizza.slice(0);
delete my_pizza[1];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With