"+var === +var" 如何在内部工作以验证 var 是否为数字?
How does "+var === +var" work internally to verify if var is numeric?
看到这个问题:Is there a (built-in) way in JavaScript to check if a string is a valid number? and this: jsperf,提出的方法之一是(mutatis mutandis):
var a = "123"
var b = "123b"
if ( +a === +a ) // true
if ( +b === +b ) // false
此逻辑如何在 JavaScript 中 内部 工作以使其成为可能?
我的问题是 而不是 如何检查字符串是否为有效数字 – 这已在此处得到解答:Validate decimal numbers in JavaScript - IsNumeric()。我想了解语句 +a === +a
的工作原理。
+"123b"
是 NaN
。 NaN is not equal to anything, including NaN.
+
将值转换为数字。
a
转换为 123
和 123 === 123
.
b
被转换为 NaN
但 NaN !== NaN
(因为 NaN
根据 step 4a of the equality rules 永远不等于另一个 NaN
)。
此处的 +
运算符称为 Unary Plus。
The unary plus operator precedes its operand and evaluates to its operand but attempts to converts it into a number, if it isn't already.
+"123"
计算为 123
.
+a === +a
-> +"123" === +"123"
-> 123 === 123
-> true
+"123b"
计算为 NaN
(Not a Number),因为 b
字符不能用一元加号转换,因为没有任何前缀(如 0x
表示十六进制)一元加号将假定该值为十进制 (0-9)。 NaN
是一个特例,因为它不与任何东西进行比较,包括它自己:
NaN === NaN
-> false
NaN !== NaN
-> true
因此,我们的 +b
测试用例失败了:
+b === +b
-> +"123b" === +"123b"
-> NaN === NaN
-> false
如果您希望两者都评估为真,我们可以在末尾添加一个 isNaN()
调用:
if ( +a === +a || isNaN(+a) )
if ( +b === +b || isNaN(+b) )
这两个变量都是字符串,但是javascript当你+或者-.
var a = "1";
var b = a; // b = "1": a string
var c = +a; // c = 1: a number
var d = -a; // d = -1: a number
基本上在您的示例中,您尝试这样做:
if ( +"123" === +"123" ) => ( 123 === 123) // true
if ( +"123b" === +"123b" ) => (NaN === NaN) // false
看到这个问题:Is there a (built-in) way in JavaScript to check if a string is a valid number? and this: jsperf,提出的方法之一是(mutatis mutandis):
var a = "123"
var b = "123b"
if ( +a === +a ) // true
if ( +b === +b ) // false
此逻辑如何在 JavaScript 中 内部 工作以使其成为可能?
我的问题是 而不是 如何检查字符串是否为有效数字 – 这已在此处得到解答:Validate decimal numbers in JavaScript - IsNumeric()。我想了解语句 +a === +a
的工作原理。
+"123b"
是 NaN
。 NaN is not equal to anything, including NaN.
+
将值转换为数字。
a
转换为 123
和 123 === 123
.
b
被转换为 NaN
但 NaN !== NaN
(因为 NaN
根据 step 4a of the equality rules 永远不等于另一个 NaN
)。
此处的 +
运算符称为 Unary Plus。
The unary plus operator precedes its operand and evaluates to its operand but attempts to converts it into a number, if it isn't already.
+"123"
计算为 123
.
+a === +a
-> +"123" === +"123"
-> 123 === 123
-> true
+"123b"
计算为 NaN
(Not a Number),因为 b
字符不能用一元加号转换,因为没有任何前缀(如 0x
表示十六进制)一元加号将假定该值为十进制 (0-9)。 NaN
是一个特例,因为它不与任何东西进行比较,包括它自己:
NaN === NaN
-> false
NaN !== NaN
-> true
因此,我们的 +b
测试用例失败了:
+b === +b
-> +"123b" === +"123b"
-> NaN === NaN
-> false
如果您希望两者都评估为真,我们可以在末尾添加一个 isNaN()
调用:
if ( +a === +a || isNaN(+a) )
if ( +b === +b || isNaN(+b) )
这两个变量都是字符串,但是javascript当你+或者-.
var a = "1";
var b = a; // b = "1": a string
var c = +a; // c = 1: a number
var d = -a; // d = -1: a number
基本上在您的示例中,您尝试这样做:
if ( +"123" === +"123" ) => ( 123 === 123) // true
if ( +"123b" === +"123b" ) => (NaN === NaN) // false