JavaScript data type conversion principle (dry goods), javascript Data Type

Source: Internet
Author: User
Tags binary to decimal

JavaScript data type conversion principle (dry goods), javascript Data Type

We all know that JavaScript is a weak (or dynamic) language, that is, the type of the variable is uncertain.

var num = 123 ; //123var num = 'HAHAHA' + num ; // "HAHAHA123"

In the above Code, the variable num is a numerical value at first, and then becomes a string. The variable type is completely determined by the current value. This type is called the weak type.

We know that in programming languages, data itself and operations are of a type.

In a strongly typed programming language, different types of variables cannot be directly computed.

However, variables of different types in the weak type language can be directly added, so the data type needs to be converted in the operation. This type of data type is automatically converted in most cases, but sometimes it needs to be manually forced conversion,

Before performing data type conversion, let's take a look at the JavaScript data types.

  • 5 basic data types: number, string, boolean, undefined, unll.
  • A complex data type: Object.

Sometimes we need to know the Data Type of a variable, we can use typeof () to operate. The return value type is string.

<script>  var arr = [undefined , true , 'world' , 123 , null , new Object , function () {}]  for ( i = 0; i < arr.length; i ++) { console.log(typeof(arr[i]));  }</script> 

The output result is undefined, boolean, string, number, object, object, and function.

Null is the basic data type. Why is the output result an Object? This is because null is considered a null Object reference. Remember.

The function is not a data type, but why does the function type appear after typeof is called. From a technical perspective, functions are objects. However, there are also some special attributes, so it is necessary to use typeof to distinguish between functions and objects.

Explicit conversion data type

1. convert non-numeric values to numeric Functions

There are three functions that can convert non-numeric values to numeric values: Number (), parseInt (), and parseFloat ().

The first function Number (mix) can be used for any data type. This function first converts the Data Type of mix to the number type, and then converts the value of mix to a value.

If the mix value can be directly converted to a number, it is directly displayed. If not, 0 or NaN is displayed.

The other two functions are used to convert a string to a value.

ParseInt (string) function: converts a string to a numeric value without rounding. Here, the string must be a string starting with a number. It is not stopped until it is traversed to the character of a non-numeric value. If it is not the beginning of a number, NaN is displayed.

<script>var num = ["123" , "124.4" , "234asd" , "asf456"] ;  for (i = 0; i < num.length; i++) {   console.log(parseInt(num[i]));  }</script>

The execution result is: 123,124,234, NaN.

ParseFloat (string): converts a string to a floating point number. Starting from the digit bit and ending with a non-digit bit, the usage is consistent with that of parseInt (string.

The parseInt () function has another usage.parseInt(string,radix):Converts a string to a decimal integer Based on radix. The value of radix is 2-32.

2. convert other types of data to string functions

There are two functions that can convert other data types to strings. ToString () and string ().

String (mix): converts a mix to a String type. This function can convert any data type value to a string.

The toString () function can be used in two ways .,

  • Usage 1: demo. toString (): converts a demo to a string type. Demo cannot be null undefined
  • Usage 2: demo. toString (radix): converts the demo in decimal format to the base number of the target. For example, 123.0.toString (8) is a string that converts a decimal number 123 to an octal value.

Note: it cannot be written as 123. toString (8) because it is parsed as a decimal number during browser parsing.

// Example: convert a binary value of 10001000 to a hexadecimal value.

// Train of thought: first convert binary to decimal, then convert from decimal to hexadecimal.

var num1 = parseInt('10001000',2);  //136var num2 = num1.toString(16);  //'88' 

3. convert a value to a Boolean value type.

Boolean (variable): converts a value to its corresponding Boolean value.

(1) Conversion Method of original type values

The Conversion Result of the following six values is false, and all other values are true.

  • Undefined
  • Null
  • -0
  • + 0
  • NaN
  • ''(Null String)

(2) object conversion rules

The Boolean value of all objects is true, and even the Boolean object corresponding to false is true.

Boolean(new Boolean(false))// true 

Note that the empty object {} and empty array [] will also be converted to true.

Boolean([]); // trueBoolean({}); // true 

Implicit data type conversion

Implicit conversions are automatically performed when the system performs operations, but all called methods are Explicit conversions.

1. Increment and decrease Operators

A ++, a --, ++ a, --

These four operators apply to any value, that is, they apply not only to integers, but also to strings, Boolean values, floating point values, and objects. At this time, they are accompanied by implicit data type conversion.

That is, first convert the variable to the Data Type of Number through number (), and then perform the increment and decrease operations.

2. (+) (-), that is, positive and negative signs

Not only applicable to integers, but also for strings, Boolean values, floating point values, and objects. Convert a variable to a data type of Number through number.

3. isNaN (variable)

The execution process is: Convert the variable through Number before isNaN ().

4. (+) plus sign

Let's take a look at the following code.

<script> var str = 1 + "1"; var num = 1 + 1; var num1 = 1 + false; document.write(str , "<br>" , num , "<br>" , num1);</script>

Execution result: 11, 2, 1

Therefore, addition has two functions. If no string exists during the operation, convert the variable to the Number type through number () before performing the operation. If there is a string, the plus sign serves as a string connection.

5.-*/% minus sign, multiplication number, division number, and remainder

Convert the data to the number type before performing the operation.

6. & |! And or non-operation

Convert the values on both sides of the operator to a Boolean type using the Boolean () function, and then perform operations. The difference is, & | returns the original value after comparison, and! The operation returns a Boolean value.

Let's look at an example.

<Script> console. log (5 & 3); // judge from left to right. If all are true, return the last true value. If one is false, returns the false value console. log (0 | 2); // judge from left to right and return the first true value. If all judgments are completed and all values are false, returns the console of the last false value. log (! 3); </script>

The returned results are 3, 2, and false.

7. <> <= >==! = Comparison operator

When the number and string are relatively large, it is implicitly converted to the number type for comparison. When the string and the string are relatively large, the size of the ascii code is compared. The return value is a Boolean value.

<Script> // 1) Comparison between pure numbers alert (1 <3); // true // 2) Comparison of numeric strings, convert it to the number alert ("1" <"3"); // true alert ("123" <"123"); // false // 3) convert a string to an ascii code alert ("a" <"B"); // true alert ("abc" <"aad"); // false, compare multiple pure letters, compare ascii codes in sequence // 4) Compare Chinese characters alert ("me ". charCodeAt (); // 25105 alert ("". charCodeAt (); // 30340 alert ("my" <"); // true, Chinese character comparison, converted to ascii code // 5) when the number and string are compared, and the string is a number. Convert the number string to the number alert (123 <"124"); // true. The following Code shows that the 124 ascii code is 49, so it is not converted into ascii comparison alert ("124 ". charCodeAt (); // 49 // 6) when the number is compared with the string, and the string is not a pure number, the non-numeric string is converted to NaN when it is converted to a number, if NaN is compared with a number, false is returned regardless of the size. alert (13> "abc"); // false </script>

The following is a special case.

<Script> // undefined does not change the type to console. log (undefined = undefined); // true console. log (undefined = 0); // false console. log (undefined> 0); // false console. log (undefined <0); // false // null does not change the type to console. log (null = null); // true console. log (null = 0); // false console. log (null> 0); // false console. log (null <0); // false console. log (undefined = null); // true console. log (NaN = NaN); // false. not a number is not equal to anything, including itself </script>

For the implicit type conversion of =, you can see the blog: http://www.bkjia.com/article/136521.htm

In the project, if we use = to determine whether the two values are equal, implicit type conversion will occur. Therefore, there are very large vulnerabilities. To solve this problem. = (Absolutely equal) and! = (Definitely not equal ).

<script> console.log(1 === "1"); //false console.log(1 === 1);   //true</script>

Summary

The above is a summary of the JavaScript data type conversion introduced by xiaobian. I hope it will be helpful to you. If you have any questions, please leave a message and I will reply to you in a timely manner. Thank you very much for your support for the help House website!

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.