javascript - 更改本地范围内的数组成员会更改全局范围内的成员

标签 javascript google-chrome scope

为什么 JavaScript 对待数组的作用域与其他变量的作用域不同?通常,如果将全局范围内的变量作为参数传递给函数,那么它就是局部变量,并且在函数内更改它不会更改全局变量的值。例如:

var globalInt = 1;
function test1(x){
    x = x + 1
}
test1(globalInt);
console.log(globalInt); //globalInt is still 1

但是,当传递值数组时,这似乎并不适用。

var globalArray = ["TEST"];

function test(x){
    x[0] = x[0].toLowerCase()
}

test(globalArray);

//globalArray is now ["test"] instead of ["TEST"]
console.log(globalArray[0]);

当我在 Chrome 中测试时,会发生这种情况,但到目前为止我还没有在其他浏览器中测试过。为什么会发生这种情况?在其他浏览器中也会发生这种情况吗?

最佳答案

这只是因为数组(它是一个对象)是通过引用传递的,而基元则不是。请注意,从技术上讲,它是按值传递的,但在本例中,值是一个引用,感谢 Esteban

A object is automatically passed by reference, without the need to specifically state it

If you pass an object (i.e. a non-primitive value, such as Array or a user-defined object) as a parameter and the function changes the object's properties, that change is visible outside the function, as shown in the following example:

MDN Link

关于javascript - 更改本地范围内的数组成员会更改全局范围内的成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36852399/

相关文章:

javascript - 无法在 Chrome 上使用 Javascript 切换全屏视频元素

javascript - AngularJS:父范围未在指令中更新(具有隔离范围)双向绑定(bind)

python - 制作全局变量的本地副本

javascript - 我的 jQuery 函数的范围?

javascript - jQuery 工具提示添加换行符

CSS,无法在 chrome 中对齐 div

javascript - 函数构造函数 - 使用原型(prototype)添加函数给出 - 未捕获的语法错误 : Unexpected token {

html - Android 版 Chrome,覆盖事件链接的蓝色

javascript - Socket.io 全局发送函数 - Node.js

javascript - 在 JavaScript 中将数组排序为 "rows"