通过完全引用传递变量 [英] Passing variable by full reference

查看:70
本文介绍了通过完全引用传递变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将一个对象或数组传递给一个函数,使其未定义,并在函数执行结束后查看更改。

I want to pass an object or array to a function, make it undefined, and see the changes after the function execution ends.

var arr = ['aaa', 'bbb', 'ccc'];
var reset = function (param) {
   param[0] = 'bbb';
   param = undefined;
}
reset(arr);

好的,结果是 ['bbb','bbb' ,'ccc'] ,但我希望它是 undefined 。是否可以有效地执行此操作?

All right, so the result is ['bbb', 'bbb', 'ccc'], but I want it to be undefined. Is it possible to do this efficiently?

推荐答案

JavaScript是按值传递语言,因此修改函数内部函数参数的值不能对作为参数传递的变量产生影响。

JavaScript is a pass by value language, so modifying the value of a function parameter inside the function cannot have an effect on the variable passed as the argument.

如果你想做类似的事情,你可以拥有自己的功能返回值:

If you want to do something like that, you can have your function return the value:

var reset = function(param) {
  // think think think
  if (whatever)
    return undefined;
  return param;
};

arr = reset(arr);

现在,如果函数决定正确的事情是清空源变量,它返回 undefined

Now, if the function decides that the right thing to do is empty out the source variable, it returns undefined.

如果您只想清除变量,则不需要函数:

If you just want to clear the variable, however, there's no need for a function:

arr = undefined;

这篇关于通过完全引用传递变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆