Home >Web Front-end >JS Tutorial >Detailed introduction to the differences between Javascript Boolean, Nnumber, and String forced type conversion_Basic knowledge

Detailed introduction to the differences between Javascript Boolean, Nnumber, and String forced type conversion_Basic knowledge

WBOY
WBOYOriginal
2016-05-16 17:46:341203browse

Let’s talk in detail about the differences between Boolean, Nnumber, and String casts in Javascript.
We know that Boolean(value) converts the value into a Boolean type, Nnumber(value) converts the value into a number (integer or floating point number), and String(value) converts the value into a string.

Let’s analyze Boolean first. Boolean returns true when the conversion value is “a string with at least one character”, “non-zero number” or “object”; when the conversion value is “empty string” ", "Number 0", "undefined", "null" returns false.
For example:

Copy code The code is as follows:

var b1 = Boolean("" );//Return false, empty string
var b2 = Boolean("s");//Return true, non-empty string
var b3 = Boolean(0);//Return false, number 0
var b4 = Boolean(1);//Return true, non-0 number
var b5 = Boolean(-1);//Return true, non-0 number
var b6 = Boolean(null); //Return false
var b7 = Boolean(undefined); //Return false
var b8 = Boolean(new Object()); //Return true, object

Next Analyze Number. Number is similar to parseInt and parseFloat. The difference is that Number converts the entire value, while parseInt and parseFloat can only convert the beginning number part.
For example:
Number(“1.2.3″), Number(“123abc”) will return NaN, while parseInt(“1.2.3″) returns 1, parseInt(“123abc”) returns 123, parseFloat( "1.2.3") returns 1.2, ParseFloat("123abc") returns 123.
Number will first determine whether the value to be converted can be completely converted, and then determine whether to call parseInt or parseFloat.
The results of calling Number are listed below:
Copy the code The code is as follows:

Number(false) //Return 0
Number(true) //Return 1
Number(undefined) //Return NaN
Number(null) //Return 0
Number("1.2 ") //Return 1.2
Number("12") //Return 12
Number("1.2.3") //Return NaN
Number(new Object()) //Return NaN
Number(123) //Return 123

Finally, let’s analyze String. String can convert all types of data into strings. For example: the result of String(false) is "false", String( The result of 1) is "1". It is somewhat different from the toString method. The difference is as follows:
Copy code The code is as follows:

var s1 = null;
var s2 = String(t1);//The value of s2 is "null"
var s3 = s1.toString();//An error will be reported
var s4;
var s5 = String(t4);//The value of s5 is "undefined"
var s6 = t4.toString();//An error will be reported
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn