Keep original array after JavaScript function
This question already has an answer here:
你应该在你的函数中克隆(创建一个你的数组的副本)
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];
}
The "pizza" array changes because the function is apparently call by reference. The function manipulates the parameters through the same location in memory that the variable outside the function is initialized in. You can avoid these unwanted changes by creating a copy of the my_pizza array and its elements, and working with that.
链接地址: http://www.djcxy.com/p/20808.html上一篇: 我无法复制数组