最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

parseint - how to parse Zero (0) as integer in JavaScript - Stack Overflow

programmeradmin2浏览0评论

I am working on a basic calculator that takes input like this " 100 + 10/2 + 3 + 0 " and returns the output in a separate field. when I break this thing into an array zero is not parsed as integer. My code is as following

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

console.log(arr);

I am working on a basic calculator that takes input like this " 100 + 10/2 + 3 + 0 " and returns the output in a separate field. when I break this thing into an array zero is not parsed as integer. My code is as following

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

console.log(arr);

Share Improve this question edited Jul 21, 2018 at 17:53 intentionally-left-nil 8,2748 gold badges39 silver badges61 bronze badges asked Jul 21, 2018 at 17:48 rudrarudra 2001 gold badge1 silver badge12 bronze badges
Add a comment  | 

4 Answers 4

Reset to default 13

Zero is a falsy value, so short-circuiting won't work here. You need to check explicitly

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

It's because 0 is falsy so after the parseInt("0") returns falsy you end up getting the string

Try using isNaN() instead

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"]

Similar to other answers, zero is falsey. However, parseInt returns NaN upon failure, and that can be used to build the answer as follows:

let arr = ["100", "+", "0"];
arr = arr.map((x) => {
  const parsed = parseInt(x);
  return Number.isNaN(parsed) ? x : parsed;
});
console.log(arr);

IMO this is a better solution as it is explicit about the return types that parseInt returns, and doesn't rely on type coercion.

Note: There are fun nuances with isNaN. The ES2015 Number.isNaN is used here to prevent any issues with type coercion, although it's not strictly necessary in this case.

parseInt("0") is falsy. You can use Number() to convert 0 to an integer.

Try the following:

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

console.log(arr);

发布评论

评论列表(0)

  1. 暂无评论