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