为什么 parseInt(string@2019) return NaN in JavaScript?
Why does parseInt(string@2019) return NaN in JavaScript?
我是 JavaScript 的新手,目前了解有关 parseInt() 方法的两件事:
parseInt("100") // gives 100
parseInt("2019@string") // gives 2019
但是,为什么 parseInt("string@2019") 会给出 NaN?
如果您查看 W3Schools page for parseInt
:
就可以看到问题
If the first character cannot be converted to a number, parseInt() returns NaN.
这就是为什么以下 returns NaN
:
console.log(parseInt("O123"));
但是如果字符串中有多个数字,由 non-digit 字符分隔,那么它不会出错 - 它只会 return 第一个数字:
Only the first number in the string is returned!
console.log(parseInt("12b34"));
此信息也可在 MDN page for parseInt
:
中找到
If the first character cannot be converted to a number, NaN is returned.
parseInt
函数将字符串作为输入,并尝试将其转换为数字。 Here are some examples that use parseInt
to convert a string to a number. 您的第二个示例 parseInt("string@2019")
returns NaN 因为它 string@2019
不是有效类型。尝试只做 parseInt("2019")
.
您可以阅读更多关于 parseInt
here。
我是 JavaScript 的新手,目前了解有关 parseInt() 方法的两件事:
parseInt("100") // gives 100
parseInt("2019@string") // gives 2019
但是,为什么 parseInt("string@2019") 会给出 NaN?
如果您查看 W3Schools page for parseInt
:
If the first character cannot be converted to a number, parseInt() returns NaN.
这就是为什么以下 returns NaN
:
console.log(parseInt("O123"));
但是如果字符串中有多个数字,由 non-digit 字符分隔,那么它不会出错 - 它只会 return 第一个数字:
Only the first number in the string is returned!
console.log(parseInt("12b34"));
此信息也可在 MDN page for parseInt
:
If the first character cannot be converted to a number, NaN is returned.
parseInt
函数将字符串作为输入,并尝试将其转换为数字。 Here are some examples that use parseInt
to convert a string to a number. 您的第二个示例 parseInt("string@2019")
returns NaN 因为它 string@2019
不是有效类型。尝试只做 parseInt("2019")
.
您可以阅读更多关于 parseInt
here。