最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

JavaScript準確判斷數(shù)據(jù)類型的5 種方法深度對比

 更新時間:2026年01月12日 08:19:53   作者:程序員大華  
這篇文章主要為大家詳細介紹了JavaScript準確判斷數(shù)據(jù)類型的5 種方法深度對比,文中的示例代碼講解詳細,感興趣的小伙伴可以了解一下

在寫js的時候,很容易因為數(shù)據(jù)類型沒判斷好而出錯,比如這樣的代碼:

function calculate(a, b) {
    return a + b;
}
// 我以為是 10 + 20 = 30
calculate(10, 20); // 結(jié)果 30 對的 

// 實際上用戶輸入的是字符串和數(shù)字
calculate("10", 20); // 結(jié)果為 "1020" 

所以為了避免這種情況的出現(xiàn),我們還是要去判斷好數(shù)據(jù)類型。

JavaScript中,有幾種方式來判斷數(shù)據(jù)類型,以下是常用的方法:

1. typeof 操作符

最常用的類型判斷方法,但有一些局限性:

typeof 42;           // "number"
typeof "hello";      // "string"
typeof true;         // "boolean"
typeof undefined;    // "undefined"
typeof null;         // "object" (歷史遺留問題)
typeof {};           // "object"
typeof [];           // "object"
typeof function(){}; // "function"
typeof Symbol();     // "symbol"
typeof 42n;          // "bigint"

局限性

  • 無法區(qū)分數(shù)組、對象和 null
  • 函數(shù)返回 function
  • typeof 適合判斷基本類型,但遇到對象類型就力不從心了

2. instanceof 操作符

用于檢測構(gòu)造函數(shù)的 prototype 屬性是否出現(xiàn)在對象的原型鏈中:

[] instanceof Array;           // true
{} instanceof Object;          // true
new Date() instanceof Date;    // true
function(){} instanceof Function; // true

// 繼承關(guān)系,數(shù)組也是對象
[] instanceof Object;          // true

instanceof 的局限性:

// 基本類型用不了
42 instanceof Number;          // false
"hello" instanceof String;     // false

在跨 iframe 或不同 window 環(huán)境下可能失效(因為構(gòu)造函數(shù)不同)

3. Object.prototype .toString.call()

這是最準確、最可靠的方法,能識別所有內(nèi)置類型!

Object.prototype.toString.call(42);           // "[object Number]"
Object.prototype.toString.call("hello");      // "[object String]"
Object.prototype.toString.call(true);         // "[object Boolean]"
Object.prototype.toString.call(null);         // "[object Null]"
Object.prototype.toString.call(undefined);    // "[object Undefined]"
Object.prototype.toString.call([]);           // "[object Array]"
Object.prototype.toString.call({});           // "[object Object]"
Object.prototype.toString.call(function(){}); // "[object Function]"
Object.prototype.toString.call(Symbol());     // "[object Symbol]"
Object.prototype.toString.call(42n);          // "[object BigInt]"

我們封裝一個實用的工具函數(shù):

function getRealType(value) {
    return Object.prototype.toString.call(value)
        .slice(8, -1)          // 截取"[object "和"]"之間的內(nèi)容
        .toLowerCase();         // 轉(zhuǎn)為小寫,更友好
}

console.log(getRealType([]));        // "array"
console.log(getRealType(null));      // "null"
console.log(getRealType({}));        // "object"
console.log(getRealType(new Date())); // "date"

4. 專用方法

對于一些特殊類型,JavaScript提供了專門的判斷方法:

判斷數(shù)組:Array.isArray()

Array.isArray([]);     // true
Array.isArray({});     // false
Array.isArray("123");  // false

判斷NaN:Number.isNaN()

// 注意區(qū)別!
isNaN("hello");        // true  ← 字符串不是數(shù)字,但這樣判斷容易誤解
Number.isNaN("hello"); // false ← 更準確:只有真正的NaN才返回true
Number.isNaN(NaN);     // true

判斷有限數(shù)字:Number.isFinite()

Number.isFinite(42);     // true
Number.isFinite(Infinity); // false  ← 無窮大不是有限數(shù)字
Number.isFinite("42");   // false  ← 字符串不是數(shù)字

編寫健壯的函數(shù)

在實際開發(fā)中的應用:

場景1:安全的數(shù)字相加

function safeAdd(a, b) {
    // 確保兩個參數(shù)都是數(shù)字類型
    if (typeof a !== 'number' || typeof b !== 'number') {
        throw new Error('參數(shù)必須是數(shù)字');
    }
    return a + b;
}

safeAdd(1, 2);     // 3
safeAdd(1, "2");   // 報錯:參數(shù)必須是數(shù)字

場景2:處理多種數(shù)據(jù)類型

function processData(data) {
    // getRealType方法在第3點Object.prototype.toString.call()中有寫
    const type = getRealType(data); 
    
    switch(type) {
        case 'array':
            return data.map(item => item * 2);
        case 'object':
            return Object.keys(data).length;
        case 'string':
            return data.toUpperCase();
        case 'number':
            return data * 2;
        default:
            return '不支持的數(shù)據(jù)類型';
    }
}

console.log(processData([1, 2, 3]));    // [2, 4, 6]
console.log(processData("hello"));      // "HELLO"
console.log(processData({a: 1, b: 2})); // 2

總結(jié):選擇合適的方法

場景推薦方法示例
判斷基本類型typeoftypeof "hello" === "string"
判斷數(shù)組Array.isArray()Array.isArray([])
判斷自定義對象instanceofobj instanceof MyClass
精確類型判斷Object.prototype.toString.call()見上文工具函數(shù)
特殊值判斷專用方法Number.isNaN(), Number.isFinite()

到此這篇關(guān)于JavaScript準確判斷數(shù)據(jù)類型的5 種方法深度對比的文章就介紹到這了,更多相關(guān)JavaScript判斷數(shù)據(jù)類型內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論

东台市| 榕江县| 阿巴嘎旗| 离岛区| 类乌齐县| 文登市| 嘉善县| 镇赉县| 丰原市| 天峨县| 洛南县| 固安县| 呼和浩特市| 定日县| 古田县| 许昌县| 清涧县| 新疆| 潜江市| 定襄县| 台东县| 大港区| 张掖市| 宁强县| 庆城县| 东安县| 乐亭县| 遂宁市| 安溪县| 兰坪| 陇南市| 武陟县| 中西区| 青州市| 高雄县| 巨野县| 固安县| 咸丰县| 乐至县| 久治县| 岚皋县|