Data type conversions in JavaScript

Source: Internet
Author: User
Tags arithmetic bitwise object object

Previous words

An important feature of all programming languages is the ability to perform type conversions, and JavaScript provides developers with a number of simple types of conversion methods. JavaScript is a weakly typed language, so type conversion becomes a more complex part of it. This article describes the data type conversions in JavaScript in detail from the four aspects of converting raw values to raw values, converting objects to raw values, explicit type conversions, and implicit type conversions.

Original value converted to original value

"Undefined"

Convert to string: ' Undefined '

Convert to Number: NaN

Convert to Boolean: false

"Null"

Convert to string: ' null '

Convert to Number: 0

Convert to Boolean: false

"Boolean"

True

Convert to string: ' true '

Convert to Number: 1

False

Convert to string: ' false '

Convert to Number: 0

"Number"

10

Convert to string: ' 10 '

Convert to Boolean: true

0

Convert to string: ' 0 '

Convert to Boolean: false

NaN

Convert to string: ' NaN '

Convert to Boolean: false

Infinity

Convert to string: ' Infinity '

Convert to Boolean: true

"String"

' ABC '

Convert Boolean value: True
Convert to Number: NaN

' 123 '

Convert Boolean value: True
Convert to Number: 123

"(Space string)

Convert Boolean value: True
Convert to Number: 0

"(empty string)

Convert Boolean value: False
Convert to Number: 0

object is converted to the original value

"Boolean"

Object-To-Boolean conversion is very simple, and all objects are converted to true

Console.log (Boolean ([]));//trueconsole.log (Boolean ([]));//trueconsole.log (Boolean ({}));//trueconsole.log ( Boolean (/\d/));//true

"Number"

The process of converting an object to a number requires the following three steps:

"1" If the object has the valueof () method, which returns a raw value, JavaScript converts the original value to a number (if necessary) and returns the number

"2" Otherwise, if the object has the ToString () method, which returns a raw value, JavaScript converts it and returns

"3" Otherwise, JavaScript throws a type error exception

In summary, it is first valueof (), then ToString ()

var test1 = {    tostring:function () {        return 1;    },    valueof:function () {        return 2;}    } Console.log (number (test1));//2
var test2 = {    tostring:function () {        return 1;    },}console.log (number (test2));//1
var test3 = {};console.log (number (TEST3));//nan

In the first step, in the built-in object, only the time date () object returns the value number of the original type, so number (new Date ()) returns the milliseconds of the numeric type now to 00:00:00 January 1, 1970

Number (new Date ())//1465976459108

In the second step, the array type returns a comma-delimited string of strings of each value in the array, returns a number if there is only a number in the string, returns Nan in other cases, and, because the ToString () method of the other object does not include numbers in the string returned, So return Nan

Number ([]);//0number ([0]);//0number ([-0]);//0number ([+]);//10number ([up]);//nannumber (other objects);//nan

"String"

Similarly, the conversion of an object to a string in JavaScript follows the following steps:

"1" If the object has the ToString () method, call this method, and if it returns a primitive value, JavaScript converts the value to a string (if it is not a string itself) and returns the string result

"2" If the object does not have the ToString () method, or if the method does not return a raw value, then JavaScript calls the ValueOf () method, and if this method exists, then JavaScript calls it, and if the return value is the original value, JavaScript converts this value to a string (if it is not a string itself) and returns the string result

"3" Otherwise, JavaScript cannot get a raw value from ToString () or valueof (), so it throws a type error exception

var test1 = {    tostring:function () {        return ' 1 ';    },    valueof:function () {        return ' 2 ';    }} Console.log (String (test1));//' 1 '
var test2 = {    tostring:function () {        return {};    },    valueof:function () {        return ' 2 ';    }} Console.log (String (test2));//' 2 '
var test3 = {};console.log (String (TEST3));//[object Object]

Built-in objects inherit the ToString () method from Object objects

"1" Object type returns ' [Object Object] ' string

Console.log ({}). tostring ());//[object Object]console.log (({a:123}). ToString ());//[object Object]

"2" function type returns function code

function test () {    alert (1);//test}test.tostring ();/* "function test () {                    alert (1);//test                  }" */

The array type "3" returns a comma-delimited string that is stitched together as a string of each value in the array

Console.log ([].tostring ()),//' Console.log ([1].tostring ()),//' 1 ' console.log ([1,2,3,4].tostring ());//' 1,2,3,4 '    

"4" Time Date type returns a string representation of the time of the current time zone

Console.log (New Date ()). ToString ());//"Sun June 10:04:53 gmt+0800 (China Standard Time)"    

"5" Regular expression regexp type returns the string representation of a regular expression literal

Console.log (/ab/i.tostring ());//'/ab/i ' Console.log (/mom (and Dad (and baby)?) /gi.tostring ());//' Mom (and Dad (and baby)?)? /gi '

An explicit type conversion

Explicit type conversions are also referred to as forced type conversions, and the next step is to convert to a Boolean, to a number, and to a cast string.

"Turn into a Boolean"

To convert a value to a Boolean value you can use the Boolean () transform function

False value

Values converted to False are called false values (Falsy value), and these 7 values include undefined, NULL, +0,-0, NaN, False, "" (An empty string)

Console.log (Boolean (undefined));//falseconsole.log (Boolean (null));//falseconsole.log (Boolean (0));// Falseconsole.log (Boolean ( -0));//falseconsole.log (Boolean (NaN));//falseconsole.log (Boolean ("));// Falseconsole.log (Boolean (false));//false

[note] in the number () method, both the empty string and the blank string are converted to 0, and in the Boolean () method, the null string "" is converted to false, and the blank string "" is converted to true

Console.log (Number ("));//0console.log (Number ("));//0console.log (Boolean ("));//falseconsole.log (Boolean (")) ;//true

In addition to these 7 false values, the other values are converted to Boolean values that are true, also known as Truth (truthy value)

[Note] All objects (including empty objects) are converted to true, and even false for Boolean object new Boolean (False) is also true

Console.log (Boolean ({}));//trueconsole.log (Boolean ([]));//trueconsole.log (Boolean (New Boolean (false)));// Trueconsole.log (Boolean (false));//falseconsole.log (Boolean (new Boolean (null)));//trueconsole.log (Boolean (NULL)) ;//false

"Turn into a number"

There are 3 functions that convert a non-numeric value to a value: Number (), parseint (), and parsefloat (). where number () converts any type of value to a number, while parseint () and parsefloat () are applied only to string conversions

Number ()

When number () is called as a function instead of as a constructor, it performs a type conversion. Use the number () function to convert any type of value

Numeric value: decimal digit console.log (number (one), Numbers (011) (0x11)),//11 9 17//undefined: Turn into nannumber (undefined)//nan// Null: Turn to 0Number (NULL)//0//Boolean: True turns 1,false to 0console.log (number (true), number (false));//1 0

The number () function parses a string and then recognizes the string's preceding space and removes

"1" If the string contains only decimal or hexadecimal digits, it is converted to a decimal number

[Note 1] Number () A string that does not recognize octal digits and is processed in decimal digits

[Note 2] string ' 1.2. ' No error, but the number 1.2 will be an error.

"2" If the string is an empty string or a space string, turn to 0

"3" Other case string, then go to Nan

Console.log (number ('    123 '));//123console.log (number (' 1.2. ')); /nanconsole.log (number (1.2.)); /Error Console.log (Number ("), Number (')"),//0 0 console.log (number (' one '), number (' 011 '), number (' 0x11 '));//11 11 17console.log (Number (' abc '));//nanconsole.log (number (' 123abc '));//nan

The steps of the number () function to parse the object are described in more detail in the previous section, and will not repeat

parseint ()

The "1" parseint () is specifically used to convert a string to an integer. When a string is converted, the spaces preceding the string are ignored until the first non-whitespace character is found. If the first character is not a numeric character or a minus sign, parseint () returns Nan. If it is, continue parsing until parsing is complete or non-numeric characters are encountered

Console.log (parseint ('    123.1px '));//123console.log (parseint ('   123.1   '));//123console.log (parseint ( ' -123.1px ');//-123console.log (parseint (' a123.1px '));//nanconsole.log (parseint (' 0 123.1px '));//0

The "2" parseint () can identify various binary numbers, and the output is the arithmetic decimal number, such as 1.0 or 1. or 01 will be output at 1. In parsing octal literal strings, ECMASCRIPT3 will parse octal, but ECMAScript5 does not have the ability to parse octal

Console.log (parseint (' One ')),//11console.log (parseint (one)),//11console.log (parseint (' 11.1 '));//11console.log ( parseint (11.1));//11console.log (parseint (' 011 '));//11console.log (parseint (011));//9console.log (parseint (' 011.1 //11console.log (parseint (011.1));//Error Console.log (parseint (' 0x11 '));//17console.log (parseint (0x11));// 17console.log (parseint (' 0x11.1 '));//17console.log (parseint (0x11.1));//Error

[note] For those numbers that will be automatically converted to scientific notation, parseint will treat the notation of scientific notation as a string, leading to some strange results

Console.log (parseint (1000000000000000000000.5)); 1//equivalent to Console.log (parseint (' 1e+21 ')); 1console.log (parseint (0.0000008)); 8//equivalent to Console.log (parseint (' 8e-7 ')); 8

  【3】parseInt()The method can also accept the second parameter (between 2 and 36), which represents the binary of the parsed value, and returns the decimal number corresponding to that value. By default, parseInt the second parameter is 10, which is the default decimal to Decimal

Console.log (parseint (' One ', 2)),//3console.log (parseint (' one ', 8)),//9console.log (parseint (' 11 ', 10));// 11console.log (parseint (' 11 ', 16));//17

If the second parameter is not a numeric value, it is automatically converted to an integer. This integer must be between 2 and 36 to get a meaningful result, beyond which a nan is returned. If the second argument is 0, undefined, and null, directly ignore the

Console.log (parseint (' 10 ', 37)); NaNconsole.log (parseint (' 10 ', 1)); NaNconsole.log (parseint (' 10 ', 0)); 10console.log (parseint (' ten ', null)); 10console.log (parseint (' Ten ', undefined)); 10

If the string contains characters that are meaningless for the specified binary, only the values that can be converted are returned from the highest bit. If the highest bit cannot be converted, the Nan is returned directly

Console.log (parseint (' 1546 ', 2)); 1console.log (parseint (' 546 ', 2)); NaN

The "4" parseint () is specifically used to handle string conversion numbers, and the parseint handles non-string and numeric types when the output is Nan. However, parseint () actually contains an implicit ToString () method, so parseint ([numeric or string]) outputs the corresponding number

Console.log (parseint (null), parseint (undefined)),//nan NaNconsole.log (parseint (True), parseint (false));//nan NaNconsole.log (parseint ([]), parseint ([' 2.5px ']), parseint ([2.5])),//nan 2 2console.log (parseint ("), parseint ("), parseint ({}));//nan nan Nan

Parsefloat ()

The "1" parsefloat () is specifically used for string conversion of floating-point numbers. Similarly, whitespace before the string is ignored when parsing, until the first non-whitespace character is found and then resolved to the end of the string or to an invalid floating-point numeric character

Console.log (parsefloat ('    0123.px '));//123console.log (parsefloat ('    123.px '));//123console.log ( Parsefloat ('    123.1px '));//123.1console.log (parsefloat ('   123.1.2px   '));//123.1console.log ( parsefloat (' -123.0px '));//-123console.log (Parsefloat ('. 123.1px '));//0.123console.log (parsefloat (' 0 123px '));//0

[note] If the string conforms to the scientific notation, the corresponding conversion

Console.log (parsefloat (' 314e-2 ')); 3.14console.log (parsefloat (' 0.0314E+2 ')); 3.14

"2" parsefloat () can recognize different binary digits, but only the decimal string is parsed

Console.log (parsefloat (' One ')),//11console.log (parsefloat (one)),//11console.log (parsefloat (' 11.1 '));// 11.1console.log (parsefloat (11.1));//11.1console.log (parsefloat (' 011 '));//11console.log (parsefloat (011));// 9console.log (parsefloat (' 011.1 '));//11.1console.log (parsefloat (011.1));//Error Console.log (parsefloat (' 0x11 '));// 0console.log (parsefloat (0x11));//17console.log (parsefloat (' 0x11.1 '));//0console.log (parsefloat (0x11.1));//Error

The "3" parsefloat () is specifically used to handle string conversion of floating-point numbers, while parsefloat handles non-string and numeric types when exporting Nan. However, parsefloat () actually contains an implicit ToString () method, so parsefloat ([numeric or string]) outputs the corresponding number

Console.log (parsefloat (null), parsefloat (undefined)),//nan NaNconsole.log (Parsefloat (True), parsefloat (false));// NaN NaNconsole.log (parsefloat ([]), parsefloat ([2.1]), parsefloat ([' 2.1px ']),//nan 2.1 2.1 console.log (Parsefloat (" ), parsefloat ({}));//nan NaN

Note The result of Number (") is the result of 0,parseint (") and Parsefloat (") is Nan

"Go to String"

There are two ways to convert a value to a string, toString (), and string ()

ToString ()

The first is the ToString () method, which uses almost every value, which returns the string representation of the corresponding value.

[Note]undefined and null do not have this method

Undefined.tostring ();//error null.tostring ();//error true.tostring ();//' True ' false.tostring ();/' false ' ' abc '. toString ( );//' abc ' 1.23.toString ();//' 1.23 ' ({}). toString ();//[object object][1,2,3,4].tostring ();/' 1,2,3,4 ' (New Date ()). ToString ();//"Sun June 10:04:53 gmt+0800 (China Standard Time)"/ab/i.tostring ();//'/ab/i '

String ()

You can use the Transform function string () When you do not know whether the value to be converted is undefined or null

The transformation function string () follows the following rules:

"1" returns ' null ' if the value is null, or ' undefined ' if the value is undefined

"2" If the value is not null or undefined, call the ToString () method and return the original type value

"3" If the object is returned using the ToString () method, then the valueof () method is called to return the original type value, and if the object is returned using the valueof () method, an error will be

Implicit type conversions

Implicit type conversions, also known as automatic type conversions, have a large number of automatic type conversions in the operators and statements in JavaScript, and the rules are: what type of value is expected and the conversion function of that type is called. Similarly, implicit type conversions are divided into Booleans, converted to numeric values, and to string

"Convert to Boolean"

"1" Logical Non-operator (!) First, its operand is converted to a Boolean value, and then it is reversed. If you use two logical non-operators at the same time, you will actually simulate the behavior of a Boolean () transformation function

Console.log (!! undefined);//falseconsole.log (!! NULL);//falseconsole.log (!! 0);//falseconsole.log (!! -0);//falseconsole.log (!! NaN);//falseconsole.log (!! "); /falseconsole.log (!! FALSE);//false

The "2" conditional operator (?:) First, it will have a question mark (?) Before the first operand is converted to a Boolean value, if it is true, then the second operand is computed and the result of its calculation is returned. Otherwise, if the first operand is a false value, then the third operand is computed and the result of its calculation is returned

Console.log (True 1:0);//1console.log ({} 1:0);//1console.log ([123]? 1:0);//1console.log ('? 1:0);//0

The evaluation result of the condition of the "3" if condition statement is converted to a Boolean value, in fact the conditional operator is only a shorthand form of the conditional statement

var a = 1;if (a) {Console.log (1)};//1if (Ten) {Console.log (1)};//1

"4" Similarly, the evaluation result of the condition of the while Loop statement is also converted to a Boolean value

var a = 1;while (a) {    console.log (1);    break;};/ /1while (Ten) {    console.log (1);    break;} 1

"Convert to Digital"

The "1" arithmetic operator converts its operand to a number

var a = ' 123 '; Console.log (+a);//123console.log (a-0);//123console.log (a*1);//123console.log (A/1);//123console.log ( a%infinity);//123

[note] In operations that involve addition, when the object is converted to the original value (ToString () after valueof ()), if none of the two operands is a string, then two operands are converted to numbers

Console.log (undefined + undefined);//nanconsole.log (null + null);//0console.log (true + true);//2

The "2" bitwise operator converts its operand to a number

var a = ' 123 '; Console.log (~~a);//123console.log (A & 1);//1console.log (A | 0);//123console.log (a ^ 0);// 123console.log (a<<0);//123console.log (a>>0);//123console.log (a>>>0);//123

[note] In addition to bitwise AND (&) operations, other operators can achieve the effect of fractional rounding

"3" in operations involving relational operators (= =,! =, >=, >, <, <=), after the object is converted to the original value (valueof () after ToString ()), if at least one operand is not a string, two operands will pass number ( Transform functions into numbers for numerical comparisons

Console.log ([1] = = 1);//true, equivalent to 1 = = 1console.log ([] = = true);//false, equivalent to 0 = = 1console.log ({} > True);//false, equivalent to NaN & Gt 1console.log (' true ' <= 0);//false, equivalent to Nan <= 0

"Go to String"

"1" in operations involving the addition operator, after the object is converted to the original value (ToString () after valueof ()), the other operand is converted to a string whenever one of the operands is a string

Console.log (1 + {}),//' 1[object Object] ' Console.log (1 + [+]),//' 11,2 ' console.log (1 + new Date ());//' Fri Jul 15 2016 22:1 2:05 gmt+0800 (China Standard Time) ' Console.log (1 +/0/);//' 1/0/' console.log (' + undefined ');//' undefined ' console.log (' + null);// ' Null ' Console.log (' + false);//' false ' Console.log (' + true ');//' true '

"2" in operations involving relational operators (= =,! =, >=, >, <, <=), after the object is converted to the original value (valueof () after ToString ()), if the two operands are strings, the string is compared

Console.log (new Date () = = ' Fri 22:12:05 gmt+0800 (China Standard Time) ');//true

[note] Converting one value to another does not mean that two values are equal

Console.log (number (null));//0console.log (null = = 0);//falseconsole.log (Boolean (Nan));//falseconsole.log (Nan = = FALSE);//false

Resources

"1" es5/type conversion and test https://www.w3.org/html/ig/zh/wiki/ES5/conversion
"2" Ruan one peak JavaScript standard reference Tutorial-basic syntax http://javascript.ruanyifeng.com/grammar/conversion.html
"3" W3school-javascript Advanced Tutorial--type conversion http://www.w3school.com.cn/js/pro_js_typeconversion.asp
"4" JavaScript Definitive Guide (6th edition) 3rd Chapter type, value, and variable
"5" JavaScript Advanced Programming (3rd Edition), chapter 3rd Basic Concepts

Data type conversions in JavaScript

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.