You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

JavaScript函数参数为何修改全局数组?如何避免该问题?

Why does passing my array to a function modify the original global array?

Hey there, let's break down why this is happening and how you can fix it!

First, let's recap your code and the unexpected behavior:

var testArr = [1, 2, 3, 4, 5];
function nextInLine(arr, item) {
  arr.push(item);
  arr.shift();
}
console.log("Before: " + testArr);
nextInLine(testArr, 6);
console.log(" After: " + testArr);

Output:
Before: 1,2,3,4,5
After: 2,3,4,5,6

Your expectation that testArr shouldn't change makes total sense at first glance—after all, you're passing it as a function parameter, not referencing the global variable directly. The key here lies in how JavaScript handles reference types like arrays (and objects).

Why the original array gets modified

In JavaScript, when you pass a value to a function:

  • For primitive types (numbers, strings, booleans, etc.), you're passing a copy of the value. Any changes to the parameter inside the function won't affect the original variable.
  • For reference types (arrays, objects), you're passing a reference to the memory location where the original array/object lives. So arr inside your function isn't a new array—it's just another pointer pointing to the same array that testArr points to. That means when you call arr.push() or arr.shift(), you're modifying the actual array in memory that both variables reference.

How to avoid modifying the original array

To keep the original array intact, you need to create a copy of the array inside the function first, then perform your operations on the copy instead of the original reference. Here are a few simple ways to create a shallow copy of an array:

  • Using the spread operator (...): This is one of the most concise ways to copy an array.
  • Using Array.slice(): Calling slice() without arguments returns a copy of the entire array.
  • Using Array.from(): This method creates a new array from an existing iterable (like your original array).

Here's a modified version of your function that preserves the original array:

var testArr = [1, 2, 3, 4, 5];
function nextInLine(arr, item) {
  // Create a copy of the input array
  const newArr = [...arr];
  // Perform operations on the copy
  newArr.push(item);
  newArr.shift();
  // Return the modified copy if you need to use it elsewhere
  return newArr;
}

console.log("Before: " + testArr);
// Store the result of the function (the modified copy)
const modifiedArr = nextInLine(testArr, 6);
console.log(" After: " + testArr); // Original array is unchanged!
console.log("Modified: " + modifiedArr); // Outputs 2,3,4,5,6

A quick note: If your array contains nested objects or other arrays, these shallow copy methods will still reference the nested items. For those cases, you'd need a deep copy (like using JSON.parse(JSON.stringify(arr)) for simple structures, or a dedicated deep copy utility), but for your current use case with a simple array of numbers, a shallow copy works perfectly.

内容的提问来源于stack exchange,提问作者Andy

火山引擎 最新活动