Javascript - 有时可以修改传递给函数的数组 [英] Javascript - can modify array passed to function only sometimes

查看:64
本文介绍了Javascript - 有时可以修改传递给函数的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么第一个函数不像第二个函数那样修改原始数组?

Why does the first function not modify the original array like the second function does?

var a= [3, 4, 5];
function doesNothing(a) {
    a=[1,1,1];
}

function doesSomething(a) {
    a.push(6);
}

doesNothing(a);
console.log(a);     // [3,4,5] not [1,1,1]
doesSomething(a);
console.log(a);     //[3,4,5,6]


推荐答案

第一个函数不会尝试修改数组。它所做的只是为参数分配一个新值,当它被调用时,给出了对该数组的引用的 copy 。第一个函数中的变量 a 只是一个以对象引用作为其值的变量。赋值语句只是改变它的值,就像你的函数

The first function makes no attempt to modify the array. All it does is assign a new value to the parameter that, when it was called, was given a copy of a reference to the array. The variable a in the first function is just a variable with an object reference as its value. The assignment statement just changes its value, exactly as if your function had

    a = 5;

而不是。

请注意你'我用 a 作为参数声明了第一个函数 - 该符号 a 隐藏了 a 在函数外部。

Note that you've declared the first function with a as a parameter - that symbol a hides the a outside the function.

第二个函数确实修改了数组,因为它调用了修改它的数组对象上的方法。

The second function does modify the array because it calls a method on the array object that modifies it.

这篇关于Javascript - 有时可以修改传递给函数的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆