JavaScript 中的隱式強制和顯式強制有什麼區別?
本文將解釋 JavaScript 中隱式強制和顯式強制的區別。
隱式強制是值從一種資料型別自動轉換為另一種資料型別的過程。它也稱為型別轉換。
顯式強制是根據使用者需要進行的資料型別轉換。
示例 1
在這個例子中,讓我們學習隱式強制。
let inputValue = "5" console.log("The input variable is defined as: ") console.log(inputValue, typeof inputValue); let resultValue = Number(inputValue); console.log("
The input variable is defined as: ") console.log(resultValue, typeof resultValue);
解釋
步驟 1 − 定義一個變數:inputValue 並賦值一個整數。
步驟 2 − 向 ‘inputValue’ 新增一個空字串。現在 ‘inputValue’ 的型別從數字變為字串。
步驟 3 − 顯示值及其型別作為結果。
示例 2
在這個例子中,讓我們學習顯式強制。
let inputValue = "5" console.log("The input value is defined as a string with value: ", inputValue) let resultValue = Number(inputValue); console.log("The result value after conversion to a number is :", resultValue)
解釋
步驟 1 − 定義一個變數:inputValue 併為其賦值一個字串值。
步驟 2 − 將字串值強制轉換為整數。現在 ‘inputValue’ 的型別從字串變為數字。
步驟 3 − 顯示值及其型別作為結果。
廣告