Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

javascript - 设置JavaScript函数的默认参数值(Set a default parameter value for a JavaScript function)

I would like a JavaScript function to have optional arguments which I set a default on, which get used if the value isn't defined (and ignored if the value is passed).

(我希望JavaScript函数具有我设置了默认值的可选参数,如果未定义值,则使用该参数(如果传递值,则将其忽略)。)

In Ruby you can do it like this:

(在Ruby中,您可以这样操作:)

def read_file(file, delete_after = false)
  # code
end

Does this work in JavaScript?

(这可以在JavaScript中使用吗?)

function read_file(file, delete_after = false) {
  // Code
}
  ask by Tilendor translate from so

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

1 Reply

0 votes
by (71.8m points)

From ES6/ES2015 , default parameters are in the language specification.

(从ES6 / ES2015开始 ,默认参数位于语言规范中。)

function read_file(file, delete_after = false) {
  // Code
}

just works.

(正常工作。)

Reference: Default Parameters - MDN

(参考: 默认参数-MDN)

Default function parameters allow formal parameters to be initialized with default values if no value or undefined is passed.

(如果传递任何值未定义,则默认函数参数允许使用默认值初始化形式参数。)

You can also simulate default named parameters via destructuring :

(您还可以通过解构模拟默认的命名参数 :)

// the `= {}` below lets you call the function without any parameters
function myFor({ start = 5, end = 1, step = -1 } = {}) { // (A)
    // Use the variables `start`, `end` and `step` here
    ···
}

Pre ES2015 ,

(ES2015之前的版本)

There are a lot of ways, but this is my preferred method — it lets you pass in anything you want, including false or null.

(有很多方法,但这是我的首选方法-它使您可以传递任何想要的信息,包括false或null。)

( typeof null == "object" )

(( typeof null == "object" ))

function foo(a, b) {
  a = typeof a !== 'undefined' ? a : 42;
  b = typeof b !== 'undefined' ? b : 'default_b';
  ...
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...