为JavaScript函数设置默认参数值我希望JavaScript函数具有可选参数,并设置默认值,如果未定义值(如果传递值,则忽略该参数)。在Ruby中,您可以这样做:def read_file(file, delete_after = false)
# codeend这在JavaScript中有效吗?function read_file(file, delete_after = false) {
// Code}
3 回答
一只斗牛犬
TA贡献1784条经验 获得超2个赞
function read_file(file, delete_after) { delete_after = delete_after || "my default here"; //rest of code}
delete_after
delete_after
"my default here"
false
, null
, undefined
, 0
""
function read_file(values) { values = merge({ delete_after : "my default here" }, values || {}); // rest of code}// simple implementation based on $.extend() from jQueryfunction merge() { var obj, name, copy, target = arguments[0] || {}, i = 1, length = arguments.length; for (; i < length; i++) { if ((obj = arguments[i]) != null) { for (name in obj) { copy = obj[name]; if (target === copy) { continue; } else if (copy !== undefined) { target[name] = copy; } } } } return target;};
// will use the default delete_after valueread_file({ file: "my file" }); // will override default delete_after valueread_file({ file: "my file", delete_after: "my value" });
慕勒3428872
TA贡献1848条经验 获得超6个赞
function pick(arg, def) { return (typeof arg == 'undefined' ? def : arg);}function myFunc(x) { x = pick(x, 'my default');}
红颜莎娜
TA贡献1842条经验 获得超12个赞
function read_file(file, delete_after = false) { // Code}
默认函数参数允许使用默认值初始化形式参数,如果 无值或 未定都通过了。
// the `= {}` below lets you call the function without any parametersfunction myFor({ start = 5, end = 1, step = -1 } = {}) { // (A) // Use the variables `start`, `end` and `step` here ···}
ES 2015前,
typeof null == "object"
)
function foo(a, b) { a = typeof a !== 'undefined' ? a : 42; b = typeof b !== 'undefined' ? b : 'default_b'; ...}
添加回答
举报
0/150
提交
取消