Home > Article > Web Front-end > Javascript type conversion rule example analysis_javascript skills
Type conversion can be divided into implicit conversion and explicit conversion. The so-called implicit conversion is the automatic conversion performed by the program at runtime, while the explicit conversion is the artificial forced conversion of the type. Javascript variables are loosely typed, which can store any data type supported by Javascript, and the type of its variables can be dynamically changed at runtime. Please see the instructions
Example:
var n = 10; n = "hello CSSer!"; n = {};
In the above example, first declare the n variable and initialize its value to 10 (integer type), then assign the string "hello CSSer!" to n, then assign an object to it, and finally the type of n is an object type. It can be seen that the type of variable n is dynamic. In actual programming, we recommend not to change the type of variables frequently, because this is not good for debugging.
Because variable types in Javascript are dynamic, the concept of type conversion needs to be used during the actual execution of the program. Type conversion can be divided into implicit conversion and explicit conversion. The so-called implicit conversion is the automatic conversion performed by the program at runtime, while the explicit conversion is the artificial forced conversion of the type. This article will summarize Javascript type conversion.
Explicit conversion
By manually performing type conversion, Javascript provides the following transformation functions:
Convert to numeric type: Number(mix), parseInt(string,radix), parseFloat(string)
Convert to string type: toString(radix), String(mix)
Convert to Boolean type: Boolean(mix)
1. The Number(mix) function can convert any type of parameter mix into a numerical type. The rules are:
1. If it is a Boolean value, true and false are converted to 1 and 0 respectively
2. If it is a numeric value, return itself.
3. If it is null, return 0.
4. If it is undefined, return NaN.
5. If it is a string, follow the following rules:
6.
1. If the string contains only numbers, convert it to decimal (ignoring leading 0)
2. If the string contains a valid floating point format, convert it to a floating point value (ignoring leading 0s)
3. If it is an empty string, convert it to 0
4. If the string contains a format other than the above, convert it to NaN
7. If it is an object, call the valueOf() method of the object, and then convert the returned value according to the previous rules. If the result of the conversion is NaN, call the object's toString() method and convert the returned string value again according to the previous rules.
The following table lists the return value of valueOf() of the object:
对象 | 返回值 |
Array | 数组的元素被转换为字符串,这些字符串由逗号分隔,连接在一起。其操作与 Array.toString 和 Array.join 方法相同。 |
Boolean | Boolean 值。 |
Date | 存储的时间是从 1970 年 1 月 1 日午夜开始计的毫秒数 UTC。 |
Function | 函数本身。 |
Number | 数字值。 |
Object | 对象本身。这是默认情况。 |
String | 字符串值。 |
下面提供几个例子,你能写出它的正确结果吗:
Number("hello CSSer!");//NaN Number("0x8");//8 Number("");//0 Number("020dd");//NaN Number("070");//70 Number(true);//1
2、parseInt(string, radix)函数,将字符串转换为整数类型的数值。它也有一定的规则:
1.忽略字符串前面的空格,直至找到第一个非空字符
2.如果第一个字符不是数字符号或者负号,返回NaN
3.如果第一个字符是数字,则继续解析直至字符串解析完毕或者遇到一个非数字符号为止
4.如果上步解析的结果以0开头,则将其当作八进制来解析;如果以0x开头,则将其当作十六进制来解析
对象 | 操作 |
Array | 将 Array 的元素转换为字符串。结果字符串由逗号分隔,且连接起来。 |
Boolean | 如果 Boolean 值是 true,则返回 “true”。否则,返回 “false”。 |
Date | 返回日期的文字表示法。 |
Error | 返回一个包含相关错误信息的字符串。 |
Function | 返回如下格式的字符串,其中 functionname 是被调用 toString 方法函数的名称:
function functionname( ) { [native code] } |
Number | 返回数字的文字表示。 |
String | 返回 String 对象的值。 |
默认 | 返回 “[object objectname]”,其中 objectname 是对象类型的名称。 |
5.如果指定radix参数,则以radix为基数进行解析
小测验:
parseInt("hello CSSer!");//NaN parseInt("0x8");//8 parseInt("");//NaN parseInt("020dd");//20 parseInt("070");//70 parseInt("22.5");//22
3. The parseFloat(string) function converts a string into a floating point type value.
Its rules are basically the same as parseInt, but there are some differences: the first decimal point symbol in the string is valid, and parseFloat will ignore all leading 0s. If the string contains a number that can be parsed as an integer, it will be returned Integer value instead of floating point value.
4. toString(radix) method. All types of values except undefined and null have a toString() method, which returns a string representation of the object.
5. String(mix) function converts any type of value into a string. The rules are:
1. If there is a toString() method, call this method (without passing the radix parameter) and return the result
2. If it is null, return "null"
3. If it is undefined, return "undefined"
6. Boolean (mix) function, converts any type of value into a Boolean value.
The following values will be converted to false: false, "", 0, NaN, null, undefined, and any other values will be converted to true.
Implicit conversion
In some cases, even if we do not provide explicit conversion, Javascript will perform automatic type conversion. The main situations are:
1. Function used to detect whether it is a non-numeric value: isNaN(mix)
isNaN() function, after testing, it was found that this function will try to convert the parameter value with Number(). If the result is "non-numeric", it will return true, otherwise it will return false.
2. Increment and decrement operators (including prefix and postfix), unary positive and negative sign operators
These operators are applicable to values of any data type. For different types of values, the operator follows the following rules (after comparison, it is found that its rules are basically the same as Number() rules):
1. If it is a string containing valid numeric characters, first convert it into a numeric value (the conversion rules are the same as Number()). After performing the operation of adding and subtracting 1, the string variable becomes a numeric variable.
2. If it is a string that does not contain valid numeric characters, set the value of the variable to NaN, and the string variable becomes a numeric variable.
3. If it is a Boolean value false, first convert it to 0 and then perform the operation of adding or subtracting 1. The Boolean value variable is programmed as a numerical variable.
4. If it is a Boolean value true, first convert it to 1 and then perform the operation of adding or subtracting 1. The Boolean value variable becomes a numerical variable.
5. If it is a floating point value, perform the operation of adding or subtracting 1.
6. If it is an object, first call the valueOf() method of the object, and then apply the previous rules to the return value. If the result is NaN, the toString() method is called before the previous rules are applied. Object variables become numeric variables.
Quiz:
Perform post-increment operations on the following types of values respectively. What is the result?
“2″, ”02dd”, ””, false, 22.5, +””, -false, +new Date()
3. Addition operator
The plus sign operator is also used as a string concatenation operator in Javascript, so the rules for the plus sign operator are divided into two situations:
•If both operand values are numeric, the rules are:
1. If an operand is NaN, the result is NaN
2. If it is Infinity+Infinity, the result is Infinity
3. If it is -Infinity+(-Infinity), the result is -Infinity
4. If it is Infinity+(-Infinity), the result is NaN
5. If it is +0+(+0), the result is +0
6. If it is (-0)+(-0), the result is -0
7. If it is (+0)+(-0), the result is +0
•If one of the operand values is a string, then:
1. If both operation values are strings, concatenate them
2. If only one operation value is a string, convert the other operation values into strings and then concatenate them
3. If an operand is an object, numeric value or Boolean value, call the toString() method to obtain the string value, and then apply the previous string rules. For
undefined and null, call String() respectively to explicitly convert them to strings.
It can be seen that in the addition operation, if one operation value is of string type, the other operation value is converted into a string and finally concatenated.
4. Multiplication and division, minus operator, modulo operator
These operators are for operations, so they have something in common: if one of the operand values is not a numeric value, the Number() function is implicitly called for conversion. For detailed rules of each operation, please refer to the definition in ECMAScript.
5. Logical operators (!, &&, ||)
The logical NOT (!) operator first converts its operation value into a Boolean value through the Boolean() function, and then negates it.
Logical AND (&&) operator, if an operation value is not a Boolean value, follow the following rules for conversion:
1. If the first operand is true after conversion by Boolean(), then the second operation value is returned, otherwise the first value (not the value after conversion by Boolean()) is returned
2. If an operation value is null, return null
3. If an operation value is NaN, return NaN
4. If an operation value is undefined, return undefined
Logical OR (||) operator, if an operation value is not a Boolean value, follow the following rules:
1. If the first operation value is false after being converted by Boolean(), the second operation value is returned, otherwise the first operation value (not the value converted by Boolean()) is returned.
2. The processing rules for undefined, null and NaN are the same as logical AND (&&)
6. Relational operators (95ec6993dc754240360e28e0de8de30a, d2e24fbfa3a7d998970671c0359d3643=)
Like the above operators, the operand values of relational operators can also be of any type, so when using non-numeric types to participate in comparisons, the system also requires implicit type conversion:
1. If both operation values are numerical values, perform numerical comparison
2. If both operation values are strings, compare the character encoding values corresponding to the strings
3. If only one operation value is a numeric value, convert the other operation value into a numeric value and perform numerical comparison
4. If an operand is an object, call the valueOf() method (if the object does not have a valueOf() method, call the toString() method), and the result will be as per the previous
Rule execution comparison
5. If an operation value is a Boolean value, convert it to a numerical value and then compare it
Note: NaN is a very special value. It is not equal to any type of value, including itself. At the same time, it returns false when compared with any type of value.
7. Equality operator (==)
The equality operator performs implicit conversion on the operation values before comparison:
1. If an operation value is a Boolean value, convert it to a numeric value before comparison
2. If one operation value is a string and the other operation value is a numeric value, convert the string into a numeric value through the Number() function
3. If one operation value is an object and the other is not, the valueOf() method of the object is called, and the results are compared according to the previous rules
4.null and undefined are equal
5. If an operation value is NaN, the equality comparison returns false
6. If both operation values are objects, compare whether they point to the same object