Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
310 views
in Technique[技术] by (71.8m points)

javascript - 有没有更好的方法在JavaScript中执行可选的函数参数? [重复](Is there a better way to do optional function parameters in JavaScript? [duplicate])

This question already has an answer here:

(这个问题在这里已有答案:)

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

(我总是在JavaScript中处理可选参数,如下所示:)

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?

(那会失败吗?)

  ask by Mark Biek translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

(如果传递了OptionalArg,您的逻辑将失败,但计算结果为false - 请尝试将此作为替代方法)

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

Or an alternative idiom:

(或另类成语:)

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

Use whichever idiom communicates the intent best to you!

(使用哪个成语最能传达您的意图!)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...