Type Conversions
運算符號和函式會自動把值轉換成正確的類型,像是 alert 把值轉換成 string,運算符號把值轉換成數字、有些情況我們需要把值轉換成需要的類型。
ToString
let value = true;
alert(typeof value); // boolean
value = String(value); // now value is a string "true"
alert(typeof value); // string
ToNumber
運算是跟函式都可以轉換成數字。
alert( "6" / "2" ); // 3, operator strings are converted to numbers
let str = "123";
alert(typeof str); // string
let num = Number(str); // becomes a number 123
alert(typeof num); // number
如果轉換的值不是數字,會顯示 NaN
。
let age = Number("an arbitrary string instead of a number");
alert(age); // NaN, conversion failed
轉換數字的規則:
Value
Becomes…
undefined
NaN
null
0
true and false
1
and 0
string
Whitespaces from the start and end are removed. If the remaining string is empty, the result is 0
. Otherwise, the number is “read” from the string. An error gives NaN
.
+ 運算符號是例外,如果其中一個值是 string
會變成字串相加,而不是轉換成數字。
alert( 1 + '2' ); // '12' (string to the right)
alert( '1' + 2 ); // '12' (string to the left)
ToBoolean
轉換布林值規則:
Value
Becomes…
0
, null
, undefined
, NaN
, ""
false
any other value
true
alert( Boolean("0") ); // true
alert( Boolean(" ") ); // spaces, also true (any non-empty string is true)
Last updated
Was this helpful?