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

JavaScript: convert string/number to a number or null, return 0 for 0?

本文关键字:数字 null 返回 转换 字符串 JavaScript      更新时间:2023-09-26

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

var b = {
   items: +a || null
};

如果a是字符串或大于0的数字,则将b.items设置为数字;如果anull/undefined,则将其设置为null

但是,如果a为0,它也会返回null。现在我想更改它,使其在a为0的情况下返回0。(这似乎是处理真实数据的正确方法:如果它是零,我们想知道它是零;如果它不存在,我们也想知道。(

我看了这个问题,试了两个:

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

但是如果CCD_ 10为空,则这两者都返回0。它们应该返回null。

如果a为0,有没有办法返回0,如果未定义,有没有方法返回null

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

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

您可以专门测试空和未定义的

var b = {
    items: ('undefined' === typeof a || null === a) ? null : +a
};

您可以在三元运算符中检查a的类型。

var b = {
    items: typeof (+a) == 'number' ? +a : null
};

演示:

var b = {
  items: typeof (+"0") == 'number' ? +"0" : null
};
alert(b.items);

编辑

破解以检查null

function f(a) {
  return isNaN('' + a) ? null : parseFloat(a)
}
alert(f(0));
alert(f(null));
alert(f(undefined));

试试这个

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

这也应该起作用:

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

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