Home  >  Article  >  Web Front-end  >  Javascript cast type conversion function_javascript skills

Javascript cast type conversion function_javascript skills

WBOY
WBOYOriginal
2016-05-16 18:52:49952browse

1. Boolean(value): Convert the value to Boolean type;
2. Nnumber(value): Convert the value to a number (integer or floating point number);
3. String(value): Convert the value into a string.
Let’s look at Boolean() first: When the value to be converted is "a string of at least one character", "a non-zero number" or an "object", then Boolean() will return true. If the value to be converted is If it is "empty string", "number 0", "undefined", "null", then Boolean() will return false. You can use the following code to test

Copy the code The code is as follows:

var t1 = Boolean( "");//Return false, empty string
var t2 = Boolean("s");//Return true, non-empty string
var t3 = Boolean(0);//Return false, Number 0
var t3 = Boolean(1),t4 = Boolean(-1);//return true, non-0 number
var t5 = Boolean(null),t6 = Boolean(undefined);//return false
var t7 = Boolean(new Object());//return true, object

Let’s look at Number() again: Number() is similar to parseInt() and parseFloat(), The difference between them 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, and 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 following lists the results of calling Number() on some values:
Number(false) 0
Number(true) 1
Number(undefined) NaN
Number(null) 0
Number( "1.2") 1.2
Number("12") 12
Number("1.2.3") NaN
Number(new Object()) NaN
Number(123) 123
Finally It's String(): This one is relatively simple. It can convert all types of data into strings, such as: String(false)---"false", String(1)---"1". It is somewhat different from the toString() method. The difference is:
Copy code The code is as follows:

var t1 = null;
var t2 = String(t1);//The value of t2 is "null"
var t3 = t1.toString();//An error will be reported here
var t4;
var t5 = String(t4);//The value of t5 is "undefined"
var t6 = t4.toString();//An error will be reported here
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