如何在JavaScript中将Zero(0)解析为整数

rud*_*dra 4 javascript parseint

我正在研究一个基本的计算器,它接受这样的输入 " 100 + 10/2 + 3 + 0 "并在单独的字段中返回输出.当我将这个东西分解成数组时,零不会被解析为整数.我的代码如下

var arr = ["100", "+", "0"];
arr = arr.map(x => parseInt(x) || x);

console.log(arr);
Run Code Online (Sandbox Code Playgroud)

31p*_*piy 9

零是一个假值,因此短路在这里不起作用.你需要明确检查

var arr = ["100", "+","0"];
arr = arr.map( x => x == 0 ? 0 : (parseInt(x) || x));
console.log(arr);
Run Code Online (Sandbox Code Playgroud)


cha*_*tfl 6

这是因为0是假的所以在parseInt("0")返回falsy之后你最终得到了字符串

尝试使用isNaN()替代

var arr = ["100", "+","0"];
arr = arr.map( x => isNaN(x) ? x : parseInt(x) );

// use F12 to see the console
console.log(arr); // output is being display as [100, "+","0"]
Run Code Online (Sandbox Code Playgroud)