“+ var === + var”是怎么回事?在内部工作以验证var是否为数字? [英] How does "+var === +var" work internally to verify if var is numeric?
问题描述
看到这个问题: JavaScript中是否有(内置)方式来检查字符串是否为有效数字?并且: jsperf ,提出的方法之一就是这样(经过必要的修改):
Seeing this question: Is there a (built-in) way in JavaScript to check if a string is a valid number? and this: jsperf, one of the presented approaches is this (mutatis mutandis):
var a = "123"
var b = "123b"
if ( +a === +a ) // true
if ( +b === +b ) // false
这个逻辑如何工作<在JavaScript中使用em> internal 来实现这一目标吗?
How does this logic work internally in JavaScript to make this possible?
我的问题是不如何检查字符串是否为有效数字&ndash的;这已在此处得到解答:验证JavaScript中的十进制数 - IsNumeric()。我想了解语句 + a === + a
是如何工作的。
My question is not how to check if a string is a valid number – this is already answered here: Validate decimal numbers in JavaScript - IsNumeric(). I want to understand how the statement +a === +a
works.
推荐答案
+
将值转换为数字。
a
转换为 123
和 123 === 123
。
b
转换为 NaN
但 NaN!== NaN
(因为 NaN
永远不等于另一个 NaN
根据平等规则的第4a步。
b
gets converted to NaN
but NaN !== NaN
(because NaN
is never equal to another NaN
according step 4a of the equality rules).
这篇关于“+ var === + var”是怎么回事?在内部工作以验证var是否为数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!