JavaScript:将字符串/数字转换为数字或null,返回0表示0?

时间:2015-07-15 14:43:09

标签: javascript

在我的JavaScript中,我目前有这个很好的表达方式:

char array

如果var b = { items: +a || null }; 是字符串,或者数字大于0,则将b.items设置为数字;如果anull /,则将a设置为null / undefined

但是,如果null为0,它也会返回a。现在我想更改它,以便a为0时返回0(这似乎是处理实际数据的正确方法:如果它为零,我们想要知道它为零,如果它不存在,我们也想知道它。)

我看了at this question并尝试了这两个:

items: 1/a ? +a: null
items: isNaN(a) ? null : +a

但如果a为null,则这两者都返回0。它们应该返回null。

如果a为0,是否可以返回0,如果未定义,我可以null

更新:以下是表达式需要执行的所有操作的摘要:

"72" -> 72
"0" -> 0
1 -> 1
0 -> 0
null -> null
undefined -> null

3 个答案:

答案 0 :(得分:1)

您可以专门测试null和undefined

Error(2,1): PLS-00103: Encountered the symbol "DECLARE" when expecting one of the following:     begin function pragma procedure subtype type <an identifier>    <a double-quoted delimited-identifier> current cursor delete    exists prior external language The symbol "begin" was substituted for "DECLARE" to continue. 

答案 1 :(得分:0)

试试这个

var b = {
   items: +a ||(a==0?0:null)
};

答案 2 :(得分:0)

这也应该有效:

var b = {
   items: a != null? +a : null
};

基于https://stackoverflow.com/a/15992131/1494833

相关问题