首頁 web前端 js教程 Javascript型別轉換的規則實例解析_javascript技巧

Javascript型別轉換的規則實例解析_javascript技巧

May 16, 2016 pm 03:13 PM

型別轉換可以分為隱式轉換和明確轉換,所謂隱式轉換即程式在執行時進行的自動轉換,明確轉換則是人為的對型別進行強制轉換。 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.如果兩個操作值都是對象,則比較它們是否指向同一個對象

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

熱門話題

Java教學
1662
14
CakePHP 教程
1419
52
Laravel 教程
1312
25
PHP教程
1262
29
C# 教程
1235
24
神秘的JavaScript:它的作用以及為什麼重要 神秘的JavaScript:它的作用以及為什麼重要 Apr 09, 2025 am 12:07 AM

JavaScript是現代Web開發的基石,它的主要功能包括事件驅動編程、動態內容生成和異步編程。 1)事件驅動編程允許網頁根據用戶操作動態變化。 2)動態內容生成使得頁面內容可以根據條件調整。 3)異步編程確保用戶界面不被阻塞。 JavaScript廣泛應用於網頁交互、單頁面應用和服務器端開發,極大地提升了用戶體驗和跨平台開發的靈活性。

JavaScript的演變:當前的趨勢和未來前景 JavaScript的演變:當前的趨勢和未來前景 Apr 10, 2025 am 09:33 AM

JavaScript的最新趨勢包括TypeScript的崛起、現代框架和庫的流行以及WebAssembly的應用。未來前景涵蓋更強大的類型系統、服務器端JavaScript的發展、人工智能和機器學習的擴展以及物聯網和邊緣計算的潛力。

JavaScript引擎:比較實施 JavaScript引擎:比較實施 Apr 13, 2025 am 12:05 AM

不同JavaScript引擎在解析和執行JavaScript代碼時,效果會有所不同,因為每個引擎的實現原理和優化策略各有差異。 1.詞法分析:將源碼轉換為詞法單元。 2.語法分析:生成抽象語法樹。 3.優化和編譯:通過JIT編譯器生成機器碼。 4.執行:運行機器碼。 V8引擎通過即時編譯和隱藏類優化,SpiderMonkey使用類型推斷系統,導致在相同代碼上的性能表現不同。

JavaScript:探索網絡語言的多功能性 JavaScript:探索網絡語言的多功能性 Apr 11, 2025 am 12:01 AM

JavaScript是現代Web開發的核心語言,因其多樣性和靈活性而廣泛應用。 1)前端開發:通過DOM操作和現代框架(如React、Vue.js、Angular)構建動態網頁和單頁面應用。 2)服務器端開發:Node.js利用非阻塞I/O模型處理高並發和實時應用。 3)移動和桌面應用開發:通過ReactNative和Electron實現跨平台開發,提高開發效率。

Python vs. JavaScript:學習曲線和易用性 Python vs. JavaScript:學習曲線和易用性 Apr 16, 2025 am 12:12 AM

Python更適合初學者,學習曲線平緩,語法簡潔;JavaScript適合前端開發,學習曲線較陡,語法靈活。 1.Python語法直觀,適用於數據科學和後端開發。 2.JavaScript靈活,廣泛用於前端和服務器端編程。

如何使用Next.js(前端集成)構建多租戶SaaS應用程序 如何使用Next.js(前端集成)構建多租戶SaaS應用程序 Apr 11, 2025 am 08:22 AM

本文展示了與許可證確保的後端的前端集成,並使用Next.js構建功能性Edtech SaaS應用程序。 前端獲取用戶權限以控制UI的可見性並確保API要求遵守角色庫

從C/C到JavaScript:所有工作方式 從C/C到JavaScript:所有工作方式 Apr 14, 2025 am 12:05 AM

從C/C 轉向JavaScript需要適應動態類型、垃圾回收和異步編程等特點。 1)C/C 是靜態類型語言,需手動管理內存,而JavaScript是動態類型,垃圾回收自動處理。 2)C/C 需編譯成機器碼,JavaScript則為解釋型語言。 3)JavaScript引入閉包、原型鍊和Promise等概念,增強了靈活性和異步編程能力。

使用Next.js(後端集成)構建多租戶SaaS應用程序 使用Next.js(後端集成)構建多租戶SaaS應用程序 Apr 11, 2025 am 08:23 AM

我使用您的日常技術工具構建了功能性的多租戶SaaS應用程序(一個Edtech應用程序),您可以做同樣的事情。 首先,什麼是多租戶SaaS應用程序? 多租戶SaaS應用程序可讓您從唱歌中為多個客戶提供服務

See all articles