我得到了以下课程:
function Corpus(name){
this.name=name; // A string
this.recordings = []; // An array to fill
this.num = ... ; // A int number to set later
}
我的int值(num)的最佳默认值是什么,当它没有定义时?
答案 0 :(得分:3)
数字的最佳候选值是0,因此键入的是预定义的,但值未知。
这是因为JavaScript具有内部类型,即使它在我们的级别上看起来很弱。
更一般地针对不同类型:
''
null
null
null
作为旁注,正如Shomz对你的问题的回答所说的那样,保持不确定是完全合法的。这取决于你:)
答案 1 :(得分:2)
取决于你想用它做什么。保留undefined
,将其设置为false
是完全正常的,如果您打算使用它进行数学计算,则可以始终将其设置为零(0
)。
请注意,上述所有值都是假的,因此JS中的松散输入使其更为重要。
如果您想轻松检查是否已定义,请保留undefined
或false
,但不要忘记稍后按值和类型进行比较以避免错误:
this.num = false;
this.num == 0; // true - be careful with this
this.num === 0; // false - the way to go