使用 byref 传递的数组
我希望有人向我解释这一点:
function myFunction(array){
array = $.grep(array, function(n,i){return n > 1 });
}
var mainArray = [1,2,3];
myFunction(mainArray);
document.write(mainArray) // 1,2,3, but i'm expecting 2,3
但如果我做类似的事情
array[3] = 4;
来代替 $.grep
行,我会得到 1,2,3,4
。 mainArray
不应该成为 $.grep
创建的新数组吗?
I would like for someone to explain this to me:
function myFunction(array){
array = $.grep(array, function(n,i){return n > 1 });
}
var mainArray = [1,2,3];
myFunction(mainArray);
document.write(mainArray) // 1,2,3, but i'm expecting 2,3
but if i do something like
array[3] = 4;
in place of the $.grep
line, i get 1,2,3,4
. Shouldn't mainArray
become the new array created by $.grep
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不,
array
参数也是一个本地(引用)变量。该函数将一个新数组分配给该变量,但这不会影响调用者的变量。所有参数(包括引用)均按值传递。如果您修改(变异)
array
的内容,情况将会有所不同:No, the
array
parameter is also a local (reference) variable. The function assigns a new array to this variable, but that doesn't affect the caller's variables. All parameters (including references), are passed by value.If you modified (mutated) the contents of
array
, that would be different:这是由于 JavaScript 的评估策略实施。
您的函数接收对象引用的副本,该引用副本与形式参数相关联并且是其值,并且为函数内部的参数分配新值不会影响对象在函数之外(原始参考)。
这种评估策略被许多语言使用,被称为共享调用
It is due the evaluation stretegy that JavaScript implements.
Your function receives a copy of the reference to the object, this reference copy is associated with the formal parameter and is its value, and an assignment of a new value to the argument inside the function does not affect object outside the function (the original reference).
This kind of evaluation strategy is used by many languages, and is known as call by sharing