萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 類型轉換完全指南:字符串、數字、布爾、對象互轉規則與技巧

轉換總覽表

目標類型顯式轉換 (推薦)隱式/技巧轉換備註
字符串String(x)、x.toString()x + ''、templatenull/undefined 無 toString,用 String()
數字Number(x)、parseInt(x,10)、parseFloat(x)+x、x - 0、x * 1、x / 1parseInt 僅解析前綴數字;Number 整體轉換
布爾Boolean(x)!!x僅 0, '', null, undefined, NaN, false 為 false
對象Object(x)、new Type(x)Object.create(proto)基本類型轉對象為包裝對象

詳細規則與示例

1. 轉字符串

String(123)          // "123"
String(true)         // "true"
String(null)         // "null"
String(undefined)    // "undefined"
String({a:1})        // "[object Object]"
String([1,2])        // "1,2"

(123).toString()     // "123"
(123).toString(2)    // "1111011" (進制)
[1,2].toString()     // "1,2"
({}).toString()      // "[object Object]"

123 + ''             // "123" (隱式)
`${123}`             // "123" (模板字符串)

2. 轉數字

Number('123')        // 123
Number('12.34')      // 12.34
Number('')           // 0
Number('abc')        // NaN
Number(null)         // 0
Number(undefined)    // NaN
Number(true)         // 1

parseInt('123px', 10) // 123 (指定基數 10)
parseFloat('12.34')   // 12.34
+'123'                // 123 (一元加號)
'123' - 0             // 123
'123' * 1             // 123

3. 轉布爾

Boolean(0)        // false
Boolean('')       // false
Boolean(null)     // false
Boolean(undefined)// false
Boolean(NaN)      // false
Boolean(false)    // false
// 其餘皆為 true

!!'hello'         // true
!!0               // false

4. 轉對象

Object(123)              // Number {123} (包裝對象)
Object('str')            // String {"str"}
Object(true)             // Boolean {true}
Object(null)             // {} (空對象)
Object(undefined)        // {} (空對象)

new Number(123)          // 同 Object(123)
new String('str')        // 同 Object('str')
// 注意:基本類型無屬性/方法,訪問時自動裝箱為包裝對象

隱式轉換陷阱(== 比較、邏輯運算、數學運算)

== 鬼畜規則(建議永遠用 ===)

[] == ''           // true ([] → "" → 0, '' → 0)
[] == 0            // true
'0' == false       // true ('0'→0, false→0)
null == undefined  // true (唯一例外)
NaN == NaN         // false (NaN 不等於任何值)

+ 號雙重語義

1 + 2      // 3 (數學加法)
'1' + 2    // "12" (字符串拼接,任一操作數為字符串觸發)
1 + '2'    // "12"
[] + []    // "" ([]→"")
[] + {}    // "[object Object]"
{} + []    // 0 (塊語句 + 一元加號) ⚠️ 在語句開頭 {} 被視為代碼塊
({}) + []  // "[object Object]" (表達式上下文)

邏輯運算符短路返回值(非布爾)

var a = 0 || 'default';  // 'default' (返回第一個真值)
var b = 1 && 'ok';       // 'ok' (返回最後一個真值)
var c = '' || null || 5; // 5

ES6+ 新增轉換方法

  • Number.isInteger()、Number.isNaN()、Number.isFinite():不轉換參數,直接判斷。
  • Math.trunc()、Math.sign():數字處理。
  • BigInt:大整數,`BigInt(123)`,不可與 `number` 混合運算。

類型判斷最佳實踐

// 基本類型
typeof x === 'string/number/boolean/undefined/symbol/bigint/function'

// null / 數組 / 日期 / 正則 / 錯誤 / 普通對象
Object.prototype.toString.call(x) === '[object Array/Date/RegExp/Error/Null/Object]'

// 封裝通用函數
function typeOf(x) {
    if (x === null) return 'null';
    var t = typeof x;
    if (t !== 'object') return t;
    return Object.prototype.toString.call(x).slice(8, -1).toLowerCase();
}
copyright © 萬盛學電腦網 all rights reserved