(Built-in) way in JavaScript to check if a string

2018-12-31 08:47发布

I'm hoping there's something in the same conceptual space as the old VB6 IsNumeric() function?

25条回答
素衣白纱
2楼-- · 2018-12-31 09:52

Save yourself the headache of trying to find a "built-in" solution.

There isn't a good answer, and the hugely upvoted answer in this thread is wrong.

npm install is-number

In JavaScript, it's not always as straightforward as it should be to reliably check if a value is a number. It's common for devs to use +, -, or Number() to cast a string value to a number (for example, when values are returned from user input, regex matches, parsers, etc). But there are many non-intuitive edge cases that yield unexpected results:

console.log(+[]); //=> 0
console.log(+''); //=> 0
console.log(+'   '); //=> 0
console.log(typeof NaN); //=> 'number'
查看更多
登录 后发表回答