在JavaScript函数之后保留原始数组 [英] Keep original array after JavaScript function
问题描述
尽管我只有PHP的实际经验,但我肯定对此有一个简单的答案.为什么将"pizza"数组传递给函数"my_pizza"而仅对"my_pizza"进行更改,为什么会更改?如何将传递给函数的原始数组保留在函数之外?函数完成运行后,披萨数组应该没有更改.我注意到,如果更改字符串变量(pie),它将在函数运行后保持不变,这与数组不同.
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);
}
这篇关于在JavaScript函数之后保留原始数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!