最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - Calling javascript function with undefined value - Stack Overflow

programmeradmin0浏览0评论

I have a function in 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

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

I have a function in 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

test("value for a",  what i can pass here so that b type will be undefined, "value for c")
Share Improve this question edited Jun 12, 2012 at 9:24 ThiefMaster 319k85 gold badges607 silver badges646 bronze badges asked Jun 12, 2012 at 9:14 King KongKing Kong 2,9155 gold badges29 silver badges39 bronze badges 1
  • 2 Create a variable without value and use it or maybe even a non existing variable. – Michael Laffargue Commented Jun 12, 2012 at 9:16
Add a ment  | 

4 Answers 4

Reset to default 9

Simply pass undefined (without quotes):

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. 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)

You can use void operator:

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

void operator evaluates the expression and returns undefined.

发布评论

评论列表(0)

  1. 暂无评论