Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keep original array after JavaScript function [duplicate]

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
like image 967
Robert Avatar asked Oct 03 '13 21:10

Robert


2 Answers

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);
}
like image 131
Raphaël Althaus Avatar answered Nov 10 '22 12:11

Raphaël Althaus


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];
}
like image 28
Barmar Avatar answered Nov 10 '22 11:11

Barmar