JavaScript function arguments store by reference
本问题已经有最佳答案,请猛点这里访问。
不确定这是否是表达我问题的正确方式。如果我设置了以下javascript代码:
1 2 3 4 5 6 7 | var x = 5; var y = function(z) { z=7; return z; } y(x); x; |
我从函数调用中得到
这里真正的问题是您没有改变任何东西;您只是重新分配函数中的变量
1 2 3 4 5 6 7 | var x = ['test']; var y = function(z) { z=['foo']; return z; } y(x); x; // Still ['test'] |
现在,别人说的也是真的。原语不能变异。这实际上比听起来更有趣,因为以下代码可以工作:
1 2 3 4 5 6 7 | > var x = 1; > x.foo = 'bar'; "bar" > x 1 > x.foo undefined |
注意到分配给
感谢@teddhop关于此说明:
Only the value is passed for all variables, not just primitives. You
cannot change a variable in the calling code by passing it to a
function. (Granted, you can change the object or array that may be
passed; however, the variable itself remains unchanged in the calling
code.)
如果您希望
1 | x = y(x); |