我觉得我错过了一些关于 JavaScript 的基本知识。任何帮助将不胜感激。
在下面的代码中,我的函数接受一个数组作为参数。它设置一个新变量 newArr
等于 input
变量。
input = [1, 2, 3, 4, 1, 3, 4];
function test(input){
var newArr = input;
newArr.splice(0,1);
return input;
};
console.log(test(input));
现在我调用splice()
新变量上的方法。我认为这只会影响新变量,留下 input
变量不变。
然而,当我返回 input
时变量,已经按照newArr
同样的方式进行拼接。
push()
也会发生同样的情况方法。为什么是这样?如何对一个变量而不是另一个变量调用这些方法?
fiddle here
非常感谢!
最佳答案
看起来我忽略了一个事实,即我需要克隆数组,而不仅仅是将其分配给新变量。
似乎有很多方法可以做到这一点,其中一种如下所示:
input = [1, 2, 3, 4, 1, 3, 4];
function test(input){
var newArr = input.slice(0); // clones array
newArr.splice(0,1);
return input;
};
console.log(test(input));
关于javascript - Array.prototype 方法会影响函数中的多个变量吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34689307/