【问题标题】:JS if not a variable [duplicate]JS如果不是变量[重复]
【发布时间】:2013-03-28 15:52:44
【问题描述】:

所以我想编写一个带有 3 个参数的函数,第三个是可选的。我想要检查一下,如果 optional 不存在,那么给它一个默认值。有没有 IF Not 的方法?如果没有,那么最好的方法是什么?

这就是我想要的

foo.(x,y, opt){
if (!opt){opt = 1;}
......
...... 
}

这就是我所拥有的:

foo.(x,y, opt){
if (opt){}
else {opt = 1;};
......
...... 
}

【问题讨论】:

  • 我认为你的两个版本是等效的。

标签: javascript


【解决方案1】:

如果参数没有传递给函数,则为undefined

function foo( x, y, opt ){
    if( typeof opt === 'undefined' ){ 
        opt = 1;
    }
    ...
}

【讨论】:

    【解决方案2】:

    在 javascript 中,您可以像这样添加默认值:

    function foo(x,y,opt){
     if(typeof(opt)==='undefined') opt = 1;
     //your code
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-03-17
      • 2023-01-24
      • 2012-10-12
      • 1970-01-01
      • 2012-10-13
      • 1970-01-01
      • 2016-05-12
      相关资源
      最近更新 更多