亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

JavaScript中判斷數(shù)據(jù)類型的方法總結(jié)

 更新時間:2023年07月19日 16:42:40   作者:前端學(xué)習(xí)筆記_zxh  
這篇文章主要為大家詳細介紹了一些JavaScript中判斷數(shù)據(jù)類型的方法,文中的示例代碼講解詳細,具有一定的學(xué)習(xí)價值,需要的小伙伴可以了解一下

JavaScript 的數(shù)據(jù)類型

  • string:字符串
  • number:數(shù)字
  • boolean:布爾值
  • undefined:未定義
  • null:空值
  • object:對象(包括數(shù)組和函數(shù))
  • symbol:符號,獨一無二的值(ES6新增)

一、typeof的缺陷

typeof 可以判斷 string、numberboolean、undefined、symbolfunction 等類型,不可以判斷 nullobject 類型。

var str = "Hello";
var num = 123;
var bool = true;
var undf;
var nl = null;
var obj = {name: "John", age: 25};
var arr = [1, 2, 3];
var func = function() {};
var sym = Symbol("mySymbol");
console.log(typeof str);    // 輸出:string
console.log(typeof num);    // 輸出:number
console.log(typeof bool);   // 輸出:boolean
console.log(typeof undf);   // 輸出:undefined
console.log(typeof nl);     // 輸出:object
console.log(typeof obj);    // 輸出:object
console.log(typeof arr);    // 輸出:object
console.log(typeof func);   // 輸出:function
console.log(typeof sym);    // 輸出:symbol

注意:typeof 無法區(qū)分 nullObject、Array。typeof 判斷這三種類型返回都是 'object'。

二、判斷是否為數(shù)組

方法1

使用 instanceof 可以判斷數(shù)據(jù)是否為數(shù)組。

[] instanceof Array // true

需要注意的是, instanceof 不可以用來判斷是否為對象類型,因為數(shù)組也是對象。

[] instanceof Object // true
{} instanceof Object // true

方法2

constructor 也可以判斷是否為數(shù)組。

[].constructor === Array // true

方法3

Object.prototype.toString.call() 可以獲取到對象的各種類型。

Object.prototype.toString.call([]) === '[object Array]' // true
Object.prototype.toString.call({}) === '[object Object]' // true

此方法還可以用來判斷是否為 promise 對象。

let obj = new Promise()
Object.prototype.toString.call(obj) === '[object Promise]' // true

方法4

使用數(shù)組的 isArray() 方法判斷。

Array.isArray([]) // true

方法5

Object.getPrototypeOf(val) === Array.prototype // true 

三、判斷是否為對象

方法1(推薦)

Object.prototype.toString.call() 可以獲取到對象的各種類型。

Object.prototype.toString.call({}) === '[object Object]' // true

方法2

Object.getPrototypeOf(val) === Object.prototype // true

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

相關(guān)文章

最新評論