型別轉換可以分為隱式轉換和明確轉換,所謂隱式轉換即程式在執行時進行的自動轉換,明確轉換則是人為的對型別進行強制轉換。 Javascript的變數是鬆散類型的,它可以儲存Javascript支援的任何資料類型,其變數的類型可以在運行時被動態改變。請看顯示
例:
var n = 10; n = "hello CSSer!"; n = {};
上面的範例中,先宣告n變數並初始化其值為10(整數型別),接著將字串「hello CSSer!」賦值給n,接著再賦一個物件給它,最後n的型別是對象類型。可以看出變數n的類型具有動態性,實際程式設計中,我們建議不要頻繁地改變變數的類型,因為這對除錯沒有好處。
正因為Javascript中變數型別具有動態性,在程式實際執行的過程中就需要用到型別轉換的概念。類型轉換可以分為隱式轉換和明確轉換,所謂隱 式轉換即程式在執行時進行的自動轉換,而明確轉換則是人為的對類型進行強制轉換。本文將對Javascript的類型轉換進行總結。
明確轉換
透過手動進行型別轉換,Javascript提供了以下轉型函數:
轉換為數值類型:Number(mix)、parseInt(string,radix)、parseFloat(string)
轉換為字串型別:toString(radix)、String(mix)
轉換為布林類型:Boolean(mix)
1、Number(mix)函數,可以將任意型別的參數mix轉換為數值型別。其規則為:
1.如果是布林值,true和false分別轉換為1和0
2.如果是數字值,則回傳本身。
3.如果是null,回傳0.
4.如果是undefined,回NaN。
5.如果是字串,遵循以下規則:
6.
1.如果字串中只包含數字,則將其轉換為十進位(忽略前導0)
2.如果字串中包含有效的浮點格式,將其轉換為浮點數值(忽略前導0)
3.如果是空字串,將其轉換為0
4.如果字串中包含非以上格式,則將其轉換為NaN
7.如果是對象,則呼叫對象的valueOf()方法,然後依據前面的規則轉換回傳的值。如果轉換的結果是NaN,則呼叫物件的toString()方法,再次依照前面的規則轉換回傳的字串值。
下表列出了物件的valueOf()的回傳值:
对象 | 返回值 |
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 operation 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.如果有一個操作值為NaN,則回傳NaN
4.如果有一個操作值為undefined,則回傳undefined
邏輯或(||)操作符,如果一個操作值不是布林值,遵循以下規則:
1.如果第一個操作值經Boolean()轉換後為false,則傳回第二個操作值,否則傳回第一個操作值(不是Boolean()轉換後的值)
2.對於undefined、null和NaN的處理規則與邏輯與(&&)相同
6. 關係運算子(, =)
與上述運算子一樣,關係運算子的操作值也可以是任意型別的,所以使用非數值型別參與比較時也需要係統進行隱式型別轉換:
1.如果兩個操作值都是數值,則進行數值比較
2.如果兩個操作值都是字串,則比較字串對應的字元編碼值
3.如果只有一個操作值是數值,則將另一個操作值轉換為數值,進行數值比較
4.如果一個運算元是對象,則呼叫valueOf()方法(如果對象沒有valueOf()方法則呼叫toString()方法),得到的結果依照前面的
規則執行比較
5.如果一個操作值是布林值,則將其轉換為數值,再進行比較
註:NaN是非常特殊的值,它不和任何類型的值相等,包括它自己,同時它與任何類型的值比較大小時都回傳false。
7. 相等運算子(==)
相等運算子會對操作值進行隱式轉換後進行比較:
1.如果一個操作值為布林值,則在比較之前先將其轉換為數值
2.如果一個操作值為字串,另一個操作值為數值,則透過Number()函數將字串轉換為數值
3.如果一個操作值是對象,另一個不是,則呼叫對象的valueOf()方法,得到的結果按照前面的規則比較
4.null與undefined是相等的
5.如果一個操作值為NaN,則相等比較回傳false
6.如果兩個操作值都是對象,則比較它們是否指向同一個對象