新聞中心
在Javascript中,如何獲取一個變量的數(shù)據(jù)類型呢?

typeof操作符
最常用且最基本的方法就是使用typeof操作符。這個操作符可以返回一個字符串值,表示給定表達(dá)式(或者說值)所屬數(shù)據(jù)類型。
例如:
```
console.log(typeof 42); // "number"
console.log(typeof true); // "boolean"
console.log(typeof "hello world"); // "string"
console.log(typeof undefined); // "undefined"
console.log(typeof null); // "object" 注意:null被認(rèn)為是對象
從上面例子可以看到,對于數(shù)字、布爾、字符串和未定義(undefined)等基本數(shù)據(jù)類型都能夠正確地識別其數(shù)據(jù)類型。
但注意到最后一個例子輸出“object”,而不是“null”。這是因?yàn)闅v史遺留問題導(dǎo)致了null被錯誤地認(rèn)為是對象(實(shí)際上它應(yīng)該屬于特殊值)。如果想要檢測是否真正存在對象,則需要進(jìn)一步判斷。
instanceof運(yùn)算符
instanceof運(yùn)算符用來判斷某個實(shí)例是否屬于某個類。
var arr = [1, 2, 3];
console.log(arr instanceof Array); // true
console.log(arr instanceof Object); // true
var obj = { name: "John", age: 30 };
console.log(obj instanceof Object); // true
從上面例子可以看到,我們可以使用instanceof運(yùn)算符來判斷一個變量是否屬于某個類(如Array、Object等)的實(shí)例。但該方法只能用于對象類型,對于基本數(shù)據(jù)類型則會返回false。
constructor屬性
每個Javascript對象都有一個constructor屬性,它指向創(chuàng)建該對象的構(gòu)造函數(shù)。通過檢查某個變量的constructor屬性值就可以得知其所屬的數(shù)據(jù)類型。
var num = new Number(42);
console.log(num.constructor === Number); // true
var str = new String("hello world");
console.log(str.constructor === String); // true
var bool = new Boolean(true);
console.log(bool.constructor === Boolean); // true
從上面例子可以看到,我們可以通過檢查某個變量的constructor屬性值來確定其具體數(shù)據(jù)類型。注意到這種方式只適用于已經(jīng)被實(shí)例化過的對象或者包裝器(wrapper)型基本數(shù)據(jù)類型。
Object.prototype.toString方法
還有一種比較通用且可靠的方法是使用Object.prototype.toString方法。這個方法會返回當(dāng)前調(diào)用toString()方法之前最初創(chuàng)建該對象時候原型鏈中最頂端那個構(gòu)造函數(shù)名稱表示當(dāng)前變量所屬類別。
function Person(name) {
this.name = name;
}
var john = new Person("John");
console.log(Object.prototype.toString.call(john)); // "[object Object]"
console.log(Object.prototype.toString.call(arr)); // "[object Array]"
從上面例子可以看到,我們可以使用Object.prototype.toString方法來判斷某個變量的具體數(shù)據(jù)類型。該方法也適用于基本數(shù)據(jù)類型。
以上就是Javascript獲取變量類型的幾種方式。需要根據(jù)具體情況選擇不同的方式進(jìn)行判斷。網(wǎng)頁題目:如何獲取Javascript變量的類型
標(biāo)題URL:http://www.dlmjj.cn/article/copipgi.html


咨詢
建站咨詢
