[英]Proper way to convert number to string in javascript
According to tutorial by w3schools ( http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_tostring_number ), we can use toString()
method on a integer var. 根据w3schools的教程( http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_tostring_number ),我们可以在整数var上使用toString()
方法。 Kindly look at the following code: 请看下面的代码:
var num = 15;
var n = num.toString();
alert(isNaN(n));
If toString()
method is working, why isNaN(n)
returning false
? 如果toString()
方法有效,为什么isNaN(n)
返回false
?
The IsNaN
method tries converting the string passed to it back to a number, and since "15" is still actually a number, the method returns false
. IsNaN
方法尝试将传递给它的字符串转换回数字,并且由于“ 15”实际上仍然是数字,因此该方法返回false
。
See: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/isNaN 请参阅: https : //developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/isNaN
isNaN()
coerces the string '15'
into a number value before checking it. isNaN()
在检查字符串之前将字符串'15'
强制转换为数字值。
isNaN
even coerces booleans, and some falsy values into numbers. isNaN
甚至将布尔值和一些虚假的值强制转换为数字。
isNaN(true) // >> false
isNaN(false) // >> false
isNaN([]) // >> false
isNaN('') // >> false
Try using typeof
to figure out if it's a number or not 尝试使用typeof
来确定是否为数字
var num = 15;
var n = num.toString();
alert(typeof n === 'number');
isNaN() function returns true if the value is NaN, and false if not. 如果值为NaN,则isNaN()函数返回true,否则返回false。 Your code is excute alert(isNaN(15)); 您的代码是执行警报(isNaN(15));
So it is return false 所以它是假的
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.