简体   繁体   English

使用未定义的值调用javascript函数

[英]Calling javascript function with undefined value

I have a function in javascript : 我在javascript中有一个函数:

function test(a, b, c) {
    if(typeof b == "undefined")
      //do something 
    //function code
}

Now i want to call this function in such a way so that typeof b remains undefined and a & c containes value ( without reordering a , b & c ), like 现在我想以这样的方式调用此函数,以便typeof b remains undefined并且a & c containes值( 不重新排序abc ),如

test("value for a",  what i can pass here so that b type will be undefined, "value for c")

只需传递undefined (不带引号):

test("value for a", undefined, "value for c");

Any variable (that's undefined). 任何变量(未定义)。

var undefinedVar;
test("value for a", undefinedVar, "value for b");

I would suggest another approach if you know that you either pass a,b and c or you pass a and c. 如果你知道要么传递a,b和c,要么传递a和c,我会建议另一种方法。 Then do as follows 然后执行以下操作

function test(a, b, c) {
  if (arguments.length < 3){
      c = b;
      b = arguments[2]; //undefined
      //do want ever you would do if b is undefined
  }
}

In this case if you by mistake pass an undefined for b it's easier to spot because it's not interpreted as "undefined actually doesn't mean undefined but is a flag telling me to do something different" it's usually more robust to test the arguments length than to rely on the value of the parameters especially if that value can also be the result of an error (Ie. if the value is undefined) 在这种情况下,如果你错误地为b传递一个未定义的东西,它更容易被发现,因为它不被解释为“未定义实际上并不意味着未定义但是是一个标志告诉我做一些不同的事情”它通常比测试参数长度更稳健依赖于参数的值,特别是如果该值也可能是错误的结果(即,如果值未定义)

You can use void operator: 您可以使用void运算符:

test('value for a', void 0, 'value for c');

void operator evaluates the expression and returns undefined . void运算符计算expression并返回undefined

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

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