在 JavaScript 中你可以创建这样的函数:
function Cat(children) {
this.children = children || 3;
}
它的作用是创建一个带有
Cat
值的children
对象,如果你不像children
那样在函数内部传递var mimmi = new Cat();
,它将与var mimmi = new Cat(undefined);
相同,这意味着mimmi
的默认数量为 children
,即 3。
但是,唯一的问题是,如果我输入
0
,它将被计为false
,并且children
将被设置为3
,而我实际上希望将其设置为0
。
创建这样的函数但仍允许 0 的最优雅的方法是什么?
不过我真的不认为这有多好看:
function Cat(children) {
this.children = (typeof this.children == "number") ? children : 3
}
是的,ES5 中没有优雅的方法来做到这一点,你不应该使用
||
作为基元(字符串、数字、布尔值、null 和未定义)的默认值,这正是你想到的原因。
您使用
typeof
的代码几乎是正确的(应该检查只是孩子的 typeof
)并且是正确的:
function Cat(children) {
this.children = (typeof children === "number") ? children : 3
}
在 ES6 中,你可以获得默认参数,这使得它变得更好:
function Cat(children = 3) {
this.children = children; // requires a runtime that supports ES6
}
虽然更 ES6 的方式是使用
class
。
因为它是一个数值,你想要的可以使用
isNaN()
function Cat(children) {
this.children = isNaN(children) ? 3 : children;
}
正如您所发现的,0 是一个布尔值。您应该检查未定义的值。
尝试:
var Cat = function(children) {
this.children = (children === undefined) ? 3 : children;
};
我想出了一个解决方案,非常适合使用多个函数和变量来完成此操作:
function por(p, d) { // por = parameter or gate
return ((typeof p === "undefined") ? d : p);
}
其中
p
是参数,d
是默认值。
在 Cat 的情况下,你可以这样使用:
function Cat(children) {
this.children = por(children, 3);
}
“多个函数和变量”我的意思是当你需要大规模地这样做时,例如:
function ABC(a, b, c) {
this.a = por(a, 1);
this.b = por(b, 2);
this.c = por(c, 3);
}
而不是:
function ABC(a, b, c) {
this.a = ((typeof a === "undefined") ? 1 : a);
this.b = ((typeof b === "undefined") ? 2 : b);
this.c = ((typeof c === "undefined") ? 3 : c);
}
2015 年,JavaScript 获得了默认参数值,专门针对这样的情况:
function Cat(children = 3) {
this.children = children;
}
仅当默认值之前的
children
值为 undefined
时才会使用默认值(要么是因为您专门传递了该值,要么因为您根本没有为其提供参数)。
在 2020 年,JavaScript 有另一种方法来处理这个问题,即 nullish 合并运算符:
function Cat(children) {
this.children = children ?? 3;
}
仅当 3
为
children
或
undefined
时,才会使用
null
。
但在这种情况下,您需要默认参数值。