我想知道如果数字小于 10,是否可以在 JavaScript 中使用 2 位数字?
例如
10,9,8,7,6 and so on to
10,09,08,07,06 as "number data type"
是的,当数字小于 10 作为“字符串数据类型”时,可以显示 2 位数字。
if(number < 10) {
console.log(number) //number
number = "0" + number;
console.log(number) //string
}
但我想将它用作数字数据类型,所以我可以使用
if(number == 01) {
//some code here
}
这可能吗?
最佳答案
ParseInt 语法
parseInt(string, radix);
Parameters
string The value to parse. If string is not a string, then it is converted to a string (using the ToString abstract operation). Leading whitespace in the string is ignored.
radix An integer between 2 and 36 that represents the radix (the base in mathematical numeral systems) of the above mentioned string. Specify 10 for the decimal numeral system commonly used by humans. Always specify this parameter to eliminate reader confusion and to guarantee predictable behavior. Different implementations produce different results when a radix is not specified, usually defaulting the value to 10.
不要做
var number = "09";
if(number == 09) { // here it will not compare the type check the == and ===
alert("OK: " + number)
} else {
alert("PROBLEM: " + number);
}
正确答案
var number = "09";
var decimal = parseInt(number,10);
if(decimal === 09) {
alert("OK: " + decimal)
} else {
alert("PROBLEM: " + decimal);
}
在控制台中检查
var first = 10 ;
var secn = "10";
first == secn // true because both are equal.
first === secn // both are not equal by type(string and number)
var result = parseInt("010", 10) == 10; // Returns true
var result = parseInt("010") == 10; // Returns false
The Number JavaScript object is a wrapper object allowing you to work with numerical values. A Number object is created using the Number() constructor. A primitive type object number is created using the Number() function.
例子
Number('123') // 123
Number('12.3') // 12.3
Number('12.00') // 12
Number('123e-1') // 12.3
Number('') // 0
Number(null) // 0
Number('0x11') // 17
Number('0b11') // 3
Number('0o11') // 9
Number('foo') // NaN
Number('100a') // NaN
Number('-Infinity') //-Infinity
关于javascript - 如何在 JavaScript 中将字符串 "01"转换为数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35081792/