javascript - 如何在 JavaScript 中将字符串 "01"转换为数字?

标签 javascript

我想知道如果数字小于 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 语法

Reference

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

Number

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

enter image description here

Image Reference

关于javascript - 如何在 JavaScript 中将字符串 "01"转换为数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35081792/

相关文章:

javascript - 如何将包含 JSON 的 JSON NSString 从 Objective C 方法传递给 Javascript 方法

javascript - Canvas Spark 线

javascript - Jquery Chosen和asp Listbox在jquery 1.11.1和chosen 1.4.2上获取多个值

javascript - 'this' 在 Javascript 函数中指的是什么

javascript - 如何将所有 text_node nodeValue 的一部分包装在 html 元素中?

javascript - 在使用angular,angularjs和jQuery技术构建的应用程序中,处理客户端全局错误的最佳和最佳方法是什么?

javascript - 上传图片和用户详细信息

javascript - 在javascript中,使用回调执行多个异步函数的最佳实践是什么?

javascript - 在javascript中获取鼠标在图像上的点击位置?

javascript - 如何在 Javascript 中镜像哈希功能?