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;// Symbollet 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:stringconsole.log(\'b:\'+typeof b); // b:numberconsole.log(\'c:\'+typeof c); // c:booleanconsole.log(\'d:\'+typeof d); // d:objectconsole.log(\'e:\'+typeof e); // e:undefinedconsole.log(\'f:\'+typeof f); // f:symbolconsole.log(\'g:\'+typeof g); // g:objectconsole.log(\'h:\'+typeof h); // h:objectconsole.log(\'i:\'+typeof i); // i:function
所以,typeof 在判断除Object类型的对象时比较方便。
2、判断已知对象类型的方法:instanceof
console.log(\'a is string:\'+a instanceof String);// a is string:trueconsole.log(\'b is number:\'+b instanceof Number);// b is number:trueconsole.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(/^[objects(.+)]$/, \'$1\').toLowerCase();}console.log(\'a:\'+var_type(a));// a:stringconsole.log(\'b:\'+var_type(b));// b:numberconsole.log(\'c:\'+var_type(c));// c:booleanconsole.log(\'d:\'+var_type(d));// d:nullconsole.log(\'e:\'+var_type(e));// e:undefinedconsole.log(\'f:\'+var_type(f));// f:symbolconsole.log(\'g:\'+var_type(g));// g:objectconsole.log(\'h:\'+var_type(h));// h:arrayconsole.log(\'i:\'+var_type(i));// i:function
此方法虽稍显繁琐,但只需简单封装一个方法即可。
文章最后给大家推荐一个小编自己写的通用后台框架云静Admin通用后台,小编也是第一次尝试开源代码,还望大家不吝赐教。