简体   繁体   English

在 JavaScript 函数中更改数组会更改函数外的数组吗?

[英]Changing array in JavaScript function changes array outside of function?

Why the two scripts behave differently?为什么这两个脚本的行为不同? I want the to use the first script, but in the second drawData() call it changes data ;我想使用第一个脚本,但在第二个drawData()调用它更改data it's weird and not what I want to happen.这很奇怪,而不是我想要发生的事情。 The second script does not have this problem.第二个脚本没有这个问题。 Why is it like that, and how can I fix the first script?为什么会这样,我该如何修复第一个脚本?

First script does not change data :第一个脚本不会更改data

 var data = ["right"]; function drawData(arrs, type) { if (type == "percentage") { arrs[0] = "omg"; } console.log(data[0]); // Changed!? } drawData(data); drawData(data, "percentage");

Second script:第二个脚本:

 var data = "right"; function drawData(arrs, type) { if (type == "percentage") { arrs = "omg"; } console.log(data); // OK, not changed. } drawData(data); drawData(data, "percentage");

This is the difference between assignment to a local variable and mutation of the given object.这是对局部变量的赋值和给定对象的变异之间的区别。

In both pieces of code arrs is a local variable, distinct from data .在两段代码中arrs是一个局部变量,与data不同。 But the elements and other properties of arrs are exactly the same as those of data .但是元素和其他性质arrs是完全一样的那些data Making changes to those property values (which is commonly called mutation of the object/array) will be visible whether you access them via arrs or via data .无论您是通过arrs还是通过data访问它们,对这些属性值的更改(通常称为对象/数组的变异)都是可见的。 And this is exactly what the first script does.这正是第一个脚本所做的。

The second script however, does not change a property value of arrs , but assigns an entirely new value to arrs , so that now it does not share any properties any more with data .第二个脚本但是,不改变的属性值arrs ,但分配一个全新的价值arrs ,以至于现在它不与任何更多分享任何属性data This is even more apparent, because both data and arrs are primitive values which cannot mutate like explained in the previous paragraph.这更加明显,因为dataarrs都是原始值,不能像上一段中解释的那样发生变异。 But even if they were objects or arrays, and you would do the following assignment:但即使它们是对象或数组,您也会执行以下分配:

arrs = [1234];

It would not affect data .它不会影响data data would only be affected if you would assign to a property/index of arrs without assigning to arrs directly.仅当您分配给arrs的属性/索引而不直接分配给arrs data才会受到影响。

First variant modifies object passed as parameter to function (which happens to be array) - so this change is seen outside function.第一个变体修改作为参数传递给函数的对象(恰好是数组) - 所以这个变化在函数之外可见。 Second variant assigns new value to function parameter (which happens to be reference to array) but does not change array itself.第二个变体为函数参数(恰好是对数组的引用)分配新值,但不会更改数组本身。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM