let value =true;alert(typeof value); // booleanvalue =String(value); // now value is a string "true"alert(typeof value); // string
ToNumber
運算是跟函式都可以轉換成數字。
alert( "6"/"2" ); // 3, operator strings are converted to numberslet str ="123";alert(typeof str); // stringlet num =Number(str); // becomes a number 123alert(typeof num); // number
如果轉換的值不是數字,會顯示 NaN。
let age =Number("an arbitrary string instead of a number");alert(age); // NaN, conversion failed
轉換數字的規則:
+ 運算符號是例外,如果其中一個值是 string 會變成字串相加,而不是轉換成數字。
alert( 1+'2' ); // '12' (string to the right)alert( '1'+2 ); // '12' (string to the left)
ToBoolean
轉換布林值規則:
alert( Boolean("0") ); // truealert( Boolean(" ") ); // spaces, also true (any non-empty string is true)
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.