有没有更好的办法在Javascript做可选功能参数? [英] Is there a better way to do optional function parameters in Javascript?

查看:101
本文介绍了有没有更好的办法在Javascript做可选功能参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直处理可选参数在Javascript中是这样的:

I've always handled optional parameters in Javascript like this:

function myFunc(requiredArg, optionalArg){
  optionalArg = optionalArg || 'defaultValue';

  //do stuff

}

有没有更好的办法做到这一点?

Is there a better way to do it?

是否有任何情况下使用 || 一样,是要失败的?

Are there any cases where using || like that is going to fail?

推荐答案

如果optionalArg传递你的逻辑会失败,但求为假 - 试试这个作为一种替代

Your logic fails if optionalArg is passed, but evaluates as false - try this as an alternative

if (typeof optionalArg === 'undefined') { optionalArg = 'default'; }

或备选成语:

optionalArg = (typeof optionalArg === 'undefined') ? 'default' : optionalArg;

使用哪个成语最好的传达意图给你!

Use whichever idiom communicates the intent best to you!

这篇关于有没有更好的办法在Javascript做可选功能参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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