js中常用的數據類型有:
值類型(基本類型):字符串(String)、數字(Number)、布爾(Boolean)、對空(Null)、未定義(Undefined)、Symbol。
引用數據類型:對象(Object)、數組(Array)、函數(Function)。
就以上數據類型先舉幾個例子:
// 字符串(String)
let a='word';
// 數字(Number)
let b=123;
// 布爾(Boolean)
let c=true;
// 對空(Null)
let d=null;
// 未定義(Undefined)
let e;
// Symbol
let f=Symbol('123');
// 對象(Object)
let g={name:'xiangming'};
// 數組(Array)
let h=[1,2,3,4,5];
// 函數(Function)
let i=function () {
return 'done';
};
1、最常見的判斷方法:typeof
console.log('a:'+typeof a);
// a:string
console.log('b:'+typeof b);
// b:number
console.log('c:'+typeof c);
// c:boolean
console.log('d:'+typeof d);
// d:object
console.log('e:'+typeof e);
// e:undefined
console.log('f:'+typeof f);
// f:symbol
console.log('g:'+typeof g);
// g:object
console.log('h:'+typeof h);
// h:object
console.log('i:'+typeof i);
// i:function
所以,typeof 在判斷除Object類型的對象時比較方便。
2、判斷已知對象類型的方法:instanceof
console.log('a is string:'+a instanceof String);
// a is string:true
console.log('b is number:'+b instanceof Number);
// b is number:true
console.log('b is number:'+b instanceof number);
// Uncaught ReferenceError: number is not defined
注意:instanceof 後面一定要是對象類型,並且大小寫不能錯,該方法適合一些條件選擇或分支。
3、通用但很繁瑣的方法:prototype(推薦)
// 定義方法獲取變量類型
function var_type(data) {
return Object.prototype.toString.call(data).replace(/^\[object\s(.+)\]$/, '$1').toLowerCase();
}
console.log('a:'+var_type(a));
// a:string
console.log('b:'+var_type(b));
// b:number
console.log('c:'+var_type(c));
// c:boolean
console.log('d:'+var_type(d));
// d:null
console.log('e:'+var_type(e));
// e:undefined
console.log('f:'+var_type(f));
// f:symbol
console.log('g:'+var_type(g));
// g:object
console.log('h:'+var_type(h));
// h:array
console.log('i:'+var_type(i));
// i:function
此方法雖稍顯繁瑣,但只需簡單封裝一個方法即可。
文章最後給大家推薦一個小編自己寫的通用後台框架雲靜Admin通用後台,小編也是第一次嘗試開源代碼,還望大家不吝賜教。
原創文章,作者:投稿專員,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/209253.html