设置默认参数值的JavaScript函数 [英] Set a default parameter value for a JavaScript function
问题描述
我想一个JavaScript函数有我设置在默认的,如果没有定义的值,它被使用可选参数。在Ruby中,你可以做这样的:
DEF READ_FILE(文件,delete_after = FALSE)
#code
结束
和javascript中这个工作呢?
函数READ_FILE(文件,delete_after = FALSE){
// code
}
从ES6 / ES2015,默认参数是在语言规范。
函数READ_FILE(文件,delete_after = FALSE){
// code
}
只是工作。
参考:<一href=\"https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/default_parameters\">Default参数 - MDN
默认参数,允许正式参数使用默认值进行初始化,如果否值或未定义传递。
块引用>pre ES2015
有很多方法,但是这是我的preferred方法 - 它可以让你在你想要的,包括虚假或无效任何通过。 (
的typeof空==对象
)函数foo(A,B)
{
A = typeof运算一个!==未定义?答:42;
B = typeof运算b ==未定义? B:你说default_b';
...
}I would like a JavaScript function to have optional arguments which I set a default on, which gets used if the value isn't defined. In Ruby you can do it like this:
def read_file(file, delete_after = false) # code end
Does this work in JavaScript?
function read_file(file, delete_after = false) { // Code }
解决方案From ES6/ES2015, default parameters is in the language specification.
function read_file(file, delete_after = false) { // Code }
just works.
Reference: Default Parameters - MDN
Default function parameters allow formal parameters to be initialized with default values if no value or undefined is passed.
Pre 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. (
typeof null == "object"
)function foo(a, b) { a = typeof a !== 'undefined' ? a : 42; b = typeof b !== 'undefined' ? b : 'default_b'; ... }
这篇关于设置默认参数值的JavaScript函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!