数组赋值后调用pop()致原数组改变?解析数组间依赖关系
Hey there! Let's tackle your two array-related questions clearly, since they get to the heart of how reference types work in most modern languages (I'm guessing we're talking JavaScript here, given the pop() method you mentioned):
When a second array is created from the first, the dependency depends entirely on how you create the second array:
- Direct assignment (
let arr2 = arr1): The two arrays are just two different names pointing to the exact same data in memory. Any change to either array (like adding/removing elements, modifying values) will instantly reflect in the other—they're not separate arrays at all. - Shallow copy (e.g.,
let arr2 = [...arr1],arr1.slice(),Array.from(arr1)): For a one-dimensional array of primitive values (numbers, strings, booleans), this creates a fully independent array. But if the original array contains reference types (objects, other arrays), those inner elements are still shared between the two arrays. Modifying an inner object inarr2will change the same object inarr1. - Deep copy (e.g., recursive copy function,
JSON.parse(JSON.stringify(arr1))): This creates a completely separate array where every element (including nested reference types) is duplicated. There's no dependency between the two arrays—changes to one won't affect the other at all.
pop()会影响第一个数组? Let's start with a concrete example that matches your scenario, because I suspect there's a small clarification needed on what you're calling pop() on:
// Your setup let arr1 = [ [1, 2, 3], "foo" ]; // arr1[0] is an array (a reference type) let arr2 = []; arr2[0] = arr1[0]; // Assign the reference of arr1[0] to arr2[0] // If you do this: arr2[0].pop(); // Call pop() on the nested array in arr2 console.log(arr1[0]); // Outputs [1, 2]—the first array's element changed!
The root cause here is how reference types work:
- Primitive values (numbers, strings, etc.) are stored directly as values. When you assign them, you make a copy of the value—so changes to one variable don't affect the other.
- Reference types (arrays, objects, functions) are stored as pointers to a location in memory. When you assign
arr1[0]toarr2[0], you're not copying the actual array—you're copying the pointer to that array. Soarr1[0]andarr2[0]both point to the exact same array in memory.
When you call pop() on that shared array (via arr2[0].pop()), you're modifying the underlying data that both arrays reference. That's why arr1[0] shows the change too.
Quick note: If you had called arr2.pop() (the array itself, not the nested element), that would only remove the pointer from arr2—it wouldn't touch the original array in arr1 at all.
内容的提问来源于stack exchange,提问作者Tflag

