You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript中扩展数组推入另一数组:按值还是按引用?含示例疑问

在JavaScript中,扩展数组后推入另一个数组是按值还是按引用传递?

示例1

先看这段代码:

const hobbies = ['Sports', 'Cooking'];
const activeHobbies = ['Hiking'];

activeHobbies.push(...hobbies);
console.log(activeHobbies); //['Hiking', 'Sports', 'Cooking']

hobbies.push('Skiing');
console.log(hobbies); //['Sports', 'Cooking', 'Skiing']
console.log(activeHobbies); //['Hiking', 'Sports', 'Cooking']

解答

  • 用扩展语法activeHobbies.push(...hobbies)完全等同于activeHobbies.push(hobbies[0], hobbies[1]),是按值传递数组元素。
  • 扩展语法会把hobbies的元素逐个提取出来,作为独立参数传给push方法。这里的元素是字符串(原始值),原始值在传递时会复制值本身,所以activeHobbies里存的是'Sports'和'Cooking'的副本,和原hobbies数组后续的修改无关。这就是为什么给hobbies添加'Skiing'后,activeHobbies不会跟着更新。

示例2

再看这段代码:

const hobbies = ['Sports', 'Cooking'];
const activeHobbies = ['Hiking'];

activeHobbies.push(hobbies);
console.log(activeHobbies); //['Hiking', ['Sports', 'Cooking', 'Skiing']], why not ['Hiking', ['Sports', 'Cooking']] ?

hobbies.push('Skiing');
console.log(hobbies); //['Sports', 'Cooking', 'Skiing']
console.log(activeHobbies); //['Hiking', ['Sports', 'Cooking', 'Skiing']]

解答

  • 你的理解完全正确:直接执行activeHobbies.push(hobbies)时,是按引用传递数组。数组属于引用类型,传递的是指向内存中数组对象的引用,所以activeHobbies的第二个元素和hobbies指向同一个数组对象,后续修改hobbies时,activeHobbies里的数组也会同步变化。
  • 至于第一个console.log的注释是错误的:这行代码在hobbies.push('Skiing')之前执行,实际输出应该是['Hiking', ['Sports', 'Cooking']],注释里写的是执行完push('Skiing')之后的结果,属于注释失误。

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 03:50:30