如何在javascript中使用本地数组进行推送,取消移位,弹出和转换?

Tru*_*246 1 javascript arrays function

我有一个函数来描述我的问题:

function testingFunc(value) {
  var temp = value;
  console.log("temp before:    " + JSON.stringify(temp));
  console.log("arrayTest before:    " + JSON.stringify(arrayTest));
  temp.unshift(123);
  console.log("temp after unshift:    " + JSON.stringify(temp));
  console.log("arrayTest after unshift:    " + JSON.stringify(arrayTest));
  temp.push(456);
  console.log("temp after push:    " + JSON.stringify(temp));
  console.log("arrayTest after push:    " + JSON.stringify(arrayTest));
  temp.shift();
  console.log("temp after shift:    " + JSON.stringify(temp));
  console.log("arrayTest after shift:    " + JSON.stringify(arrayTest));
  temp.pop();
  console.log("temp after pop:    " + JSON.stringify(temp));
  console.log("arrayTest after pop:    " + JSON.stringify(arrayTest));
  return temp;
}

var arrayTest = [1,2,3,4,5];
var arrayTestTwo;

arrayTestTwo = testingFunc(arrayTest);
console.log("arrayTest after testingFunc:    " + JSON.stringify(arrayTest));
console.log("arrayTestTwo:    " + JSON.stringify(arrayTestTwo));
Run Code Online (Sandbox Code Playgroud)

正如你所看到的,arrayTest会太多,如果改变temp的变化通过使用push,unshift,popshift编辑它的数据.

但我希望这些功能只能用于temp和忽略arrayTest.

可能吗?也可以使用对象包含函数吗?

为什么会这样?

Frx*_*rem 5

将数组赋值给变量(或将其作为参数传递给函数)时,只存储对该数组的引用.如果两个或多个变量引用同一个数组,那么对一个变量进行更改也会影响所有其他变量:

var original = [];
var modified = original;
console.log(original, modified); // [] []

modified.push(1, 2, 3);
console.log(original, modified); // [1,2,3] [1,2,3]
Run Code Online (Sandbox Code Playgroud)

解决此问题的方法是制作数组的副本.要制作数组的副本,只需调用array.slice():

var original = [];
var modified = original.slice();
console.log(original, modified); // [] []

modified.push(1, 2, 3);
console.log(original, modified); // [] [1,2,3]
Run Code Online (Sandbox Code Playgroud)