0 与 ||操作员

问题描述 投票:0回答:5

在 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
}
javascript
5个回答
5
投票

是的,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


3
投票

因为它是一个数值,你想要的可以使用

isNaN()

function Cat(children) {
    this.children = isNaN(children) ? 3 : children;
}

0
投票

正如您所发现的,0 是一个布尔值。您应该检查未定义的值。

尝试:

var Cat = function(children) {
	this.children = (children === undefined) ? 3 : children;
};


0
投票

我想出了一个解决方案,非常适合使用多个函数和变量来完成此操作:

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);
}

0
投票

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

但在这种情况下,您需要默认参数值。

© www.soinside.com 2019 - 2024. All rights reserved.