1、对于原始数据类型String,Boolean,Undefined使用typeof方法,函数也可以使用typeof方法。
console.log(typeof "string"); // string
console.log(typeof false); // booleand
console.log(typeof undefined); // undefined
const f = function () {};
console.log(typeof f); // function
2、对于原始数据类型null,typeof方法检测null的结果是object,不能使用,可以使用null ===null来检测。
console.log(typeof null); // object
console.log(null === null); // true
3、要检测一个数据是否是对象类型,使用typeof的检测结果也是object,所以不能使用。可以使用Object.prototype.toStirng方法。
console.log(typeof {}); // object
const t = Object.prototype.toString.call({});
console.log(t); // [object Object]
4、要检测一个数据是否是数组类型,使用typeof的检测结果也是object,所以不能使用。可以使用Object.prototype.toStirng、Array.isArray,instanceof方法。
console.log(typeof []); // object
const t1 = Object.prototype.toString.call([]);
console.log(t1); // [object Array]
console.log(Array.isArray([])); // true
const a1 = [] instanceof Array;
console.log(a1); // true
5、通用的检测数据类型的方法可以用Object.prototype.toStirng。
console.log(Object.prototype.toString.call(null)); // [object Null]
console.log(Object.prototype.toString.call("null")); // [object String]
console.log(Object.prototype.toString.call({})); // [object Object]
console.log(Object.prototype.toString.call(true)); // [object Boolean]
const f1 = function () {};
console.log(Object.prototype.toString.call(f1)); // [object Function]
console.log(Object.prototype.toString.call(0)); // [object Number]
「真诚赞赏,手留余香」
真诚赞赏,手留余香
使用微信扫描二维码完成支付
转载请注明:首页 > 投稿 » js判断数据类型的方法(JavaScript检测数据类型的方法)
发表评论
版权声明
求资源网所发布的一切破解补丁,软件,以及其他分析文章仅限用于学习和研究目的;不得将上述内容用于商业或者非法用途。
否则,一切后果请用户自负。本站信息来自网络,版权争议与本站无关。您必须在下载后的24个小时之内,从您的电脑中彻底删除上述内容。如果您喜欢该程序,请支持正版软件,购买注册,得到更好的正版服务。如有侵权请邮件与我们联系处理。