js型別判斷
阿新 • • 發佈:2021-08-23
對js中元素型別判斷做個總結。
1.typeof
typeof可以區分的型別:String Number undefined Boolean Symbol BigInt。
2.Array.isArray()
是否是陣列
3.其他
除以上的資料型別還有Null、Date等,可以使用Oject.prototype.toString.call(Car).slice(8, -1).toLowerCase()
來判斷。這種方法其實概括了上述的兩種方法,在使用中直接使用次方法即可,如下示例:
> Object.prototype.toString.call([]).slice(8, -1).toLowerCase() < "array" > Object.prototype.toString.call('').slice(8, -1).toLowerCase() < "string" > Object.prototype.toString.call(1).slice(8, -1).toLowerCase() < "number"
PS: instanceof
用於檢測建構函式的 prototype 屬性是否出現在某個例項物件的原型鏈上.(也就是此例項是否繼承此類)
function Car(make, model, year) {
this.make = make;
this.model = model;
this.year = year;
}
const auto = new Car('Honda', 'Accord', 1998);
console.log(auto instanceof Car);
// true