In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article is to share with you about how many data types are converted in javascript. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.
There are two kinds of data type conversion of javascript: 1, explicit type conversion (also known as mandatory type conversion), mainly through the use of JavaScript built-in functions to convert data; 2, implicit type conversion, which refers to the type that JavaScript automatically converts values according to the computing environment.
The operating environment of this tutorial: windows7 system, javascript1.8.5 version, Dell G3 computer.
JavaScript is a weakly typed dynamically typed language. Variables have no type restrictions and can be assigned arbitrary values at any time.
Var x = y? 1:'a'
In the above code, whether the variable x is a numeric value or a string depends on the value of another variable, y. When y is true, x is a numeric value; when y is false, x is a string. This means that the type of x cannot be known at compile time, and must be known at run time.
Although the data type of a variable is uncertain, various operators have requirements for the data type. If the operator finds that the type of the operator does not match the expectation, the type is automatically converted. For example, the subtraction operator expects the operators on the left and right sides to be numeric, and if not, they are automatically converted to numeric values.
'4' -' 3' / / 1
In the above code, although the two strings are subtracted, the resulting value 1 is still obtained because JavaScript automatically converts the operator to a numeric value.
Data type conversion in javascript
In js, there are generally two types of data type conversion, namely, forced type conversion and implicit type conversion (using js weak variable type conversion).
Explicit type conversions are mainly done by using JavaScript built-in functions.
Implicit type conversion refers to the type that JavaScript automatically converts values according to the computing environment.
In js, if you want to convert an object to the original value, you must call the internal function toPrimitive (), so how does it work?
ToPrimitive (input,preferedType)
Input is the input value, preferedType is the type of expected conversion, it can be String or Number, or it can not be passed.
1) if the conversion type is number, the following steps will be performed:
1. If input is the original value, return this value directly; 2. Otherwise, if input is an object, call input.valueOf (), if the result is the original value, return the result; 3. Otherwise, call input.toString (). If the result is the original value, return the result; 4. Otherwise, throw an error.
2) if the conversion type is String,2 and 3 will exchange execution, that is, execute the toString () method first.
3) preferedType can be omitted, where the date is considered a string and other values are treated as Number.
① if input is a built-in Date type, preferedType is considered String
② is regarded as Number otherwise, call valueOf first, and then call toString
ToBoolean (argument)
Type returns the result UnderfinedfalseNullfalseBooleanargumentNumber only if argument is + 0maxim 0 or NaN, return false; otherwise return trueString only if argument is an empty string (length 0), return false; is not return trueSymboltrueObjecttrue
Note: true is returned except underfined,null,false,NaN,'',0,-0.
ToNumber (argument)
The result returned by the type UnderfinedNaNNull+0Booleanargument is true,return 1; convert the contents of the string to numbers for false,return + 0NumberargumentString, such as'23 values = > 23; if the conversion fails, return NaN, such as'23 years = > NaNSymbol throws TypeError exception Object** first primValue= toPrimitive (argument,number), use ToNumber (primValue) on primValue * *
ToString (argument)
Type returns the result Underfined "underfined" Null "null" Booleanargument is true,return "true"; use a string to represent this number for false,return "false" Number StringargumentSymbol throws a TypeError exception Object** first primValue= toPrimitive (argument,string), use ToString (primValue) for primValue * *
1. Implicit type conversion:
1.1-introduction to implicit conversion
In js, if the data on both sides of the operator are not unified, the CPU cannot be calculated. Then our compiler will automatically convert the data on both sides of the operator to the same data type and then calculate it.
This way of automatic conversion by the compiler, which does not require manual conversion by the programmer, is called implicit conversion.
For example, the line of 1 > "0" does not report an error in js. The compiler will first convert the "0" on the right to the number 0` in the operator, and then compare the size.
-
1.2-implicit conversion rules
(1)。 Convert to string type: + (string connector)
(2)。 Convert to number type: + + /-(self-increasing and self-subtracting operator) +-* /% (arithmetic operator) >
< >When one side of the xy is string, string concatenation will be done with console.log (1) / String (1) + 2 = > '1true' console.log (' axie + +'b') / / aNaN console.log (1+undefined) / / 1+Number (undefined) = = > 1+NaN=NaN console.log (null+1) / / Number (null) + 1 string = > 0 truth 1 / 2. Will convert other data types to number and then compare the relationship / / Note: when there are strings on the left and right sides, they should be converted into numbers according to the unicode encoding corresponding to the characters. The way to view the string unicode: string .charCodeAt (string subscript, default is 0) console.log ('2' > '10') / /' 2'.charCodeAt () > '10'.charCodeAt () = 50 > 49 codes = > true / / Special case, NaN is NaN console.log (NaN==NaN) / / false / / 3 compared to any data. When a complex data type is implicitly converted, the original value (valueOf ()) is not number, but will be converted to String first. Then switch to Number operation console.log (false== {}) / / false / / ({}). ValueOf (). ToString () = "[object Object]" console.log ([] + []) / "/ / [] .valueof (). ToString () + [] .valueof (). ToString () =" + "=" console.log ({} + []) / / 0 console. Log (({}) + []) / / "[object Object]" console.log (5 / [1]) / / 5 console.log (5/null) / / 5 console.log (5 + {toString:function () {return 'def'}}) / / 5def console.log (5 + {toString:function () {return' def'}) ValueOf:function () {return 3}}) / / 5 / 3 / 4. Confusion between logical non-implicit conversion and relational operator implicit conversion (logical non- Convert other types to boolean type) console.log ([] = = 0) / / true console.log ({} = = 0) / / false console.log (! [] = = 0) / / true console.log ([] = =! []) / / true console.log ([] = = []) / / false / / pit console.log ({} = = {}) / / false / / pit console.log ({} =! {}) / / false / / pit
two。 Force type (explicit type) conversion:
Through manual type conversion, Javascript provides the following transformation functions:
Convert to numeric types: Number (mix), parseInt (string,radix), parseFloat (string)
Convert to string type: toString (radix), String (mix)
Convert to Boolean type: Boolean (mix)
2.1 Boolean (value), Number (value), String (value)
New Number (value), new String (value), and new Boolean (value) pass in the values of their corresponding original types to achieve "boxing"-that is, the original types are encapsulated into an object. In fact, these three functions can be used not only as constructors, but also as ordinary functions to convert parameters of any type into values of the original type.
In fact, during the type conversion, these three functions call ToBoolean (argument), ToNumber (argument) and ToString (argument) within js.
2.2 parseInt (string,radix)
Converts a string to a numeric value of an integer type. It also has certain rules:
(1) ignore the space before the string until the first non-empty character is found
(2) if the first character is not a numeric symbol or a minus sign, return NaN
(3) if the first character is a number, continue parsing until the string is parsed or a non-numeric symbol is encountered.
(4) if the result of the previous parsing starts with 0, it is parsed as octal; if it starts with 0x, it is parsed as hexadecimal.
(5) if the radix parameter is specified, the resolution is based on radix.
Let objj= {valueOf:function () {return '2px'}, toString:function () {return []}} parseInt (objj) / / 2 parseInt (' 001') / / 1 parseInt ('22.5') / / 22 parseInt ('123sws') / / 123 parseInt (' sws123') / / NaN / / Special parseInt (function () {} 16) / / 15 parseInt (1Accord 0Magne19) / / 18 / / browser code parser: there are two parameters in parseInt The second parameter is the hexadecimal system, which is the hexadecimal system (0Power1, 2pyr2, 3, 4, 5Power6, 7, 8, 9), er, 1, 0, the result of the operation is equal to Infinity, / / the good hexadecimal system has knowledge, n hexadecimal does not exist and does not recognize, no matter whether there is later, immediately return I (18 of the corresponding decimal system of I) So return 18 parseInt / / NaN / / as above, hexadecimal annihilation corresponds to I, return NaN parseInt (0.0000008) / / 8 / / String (0.0000008), the result is 8e-7 parseInt (0.000008) / / 0 parseInt (false,16) / / 250 / / hexadecimal,'f 'know,' a 'know,' l' Oh, no Immediately return fa (hexadecimal fa converted to decimal equals 250) parseInt ('0x10') / / 16 / / there is only one parameter, OK, use the default decimal,'0x', er, this I know, is written in hexadecimal. Hexadecimal conversion of 10 to decimal equals 16 parseInt / / 2 / return binary 10 to decimal equals 2
2.3 parseFloat (string)
Converts a string to a numeric value of the floating point type. Rules:
Its rules are basically the same as parseInt, but there are some differences: the first decimal symbol in the string is valid, and parseFloat ignores all leading zeros, and if the string contains a number that can be resolved to an integer, it returns an integer value instead of a floating point value.
2.4 toString (radix)
All types of values except undefined and null have a toString () method, which returns a string representation of the object
Thank you for reading! This is the end of this article on "how many data type conversions are in javascript". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it for more people to see!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
I used to use GridView and Acti to do paging.
© 2024 shulou.com SLNews company. All rights reserved.