JS判断数据类型的4种方法
2018-10-10 19:03
369 查看
版权声明:本文为博主原创文章,欢迎交流分享,未经博主允许不得转载。 https://blog.csdn.net/Jeffid/article/details/83001836
4种判断方法分别是:
- typeof
- instanceof
- prototype属性
- constructor属性
可判断的类型对比如下图:
// 构造函数名方法 function getConstructorName(data) { return (data === undefined || data === null) ? data : (data.constructor && data.constructor.toString().match(/function\s*([^(]*)/)[1]); } // 对象原型方法 // 不能判断自定义函数对象类型 function getPrototypeName(data) { return Object.prototype.toString.call(data).slice(8, -1); } // 自定义的构造函数 function Func() { this.attr = 33; } var newObj = new Func(), num = 123, arr = []; console.group("检测自定义构造函数实例"); console.log(getConstructorName(newObj)); // Func console.log(getPrototypeName(newObj)); // Object ;仅能识别为对象 console.log(newObj instanceof Func); // true console.log(typeof newObj); // object ;仅能识别为对象 console.groupEnd(); console.group("检测数值类"); console.log(getConstructorName(num)); // Number console.log(getPrototypeName(num)); // Number // console.log(num instanceof Number); // 数值类不是对象不能使用该方法 console.log(typeof num); // number console.groupEnd(); console.group("检测数组类"); console.log(getConstructorName(arr)); // Array console.log(getPrototypeName(arr)); // Array console.log(arr instanceof Array); // true console.log(typeof arr); // object ;仅能识别为对象 console.groupEnd();
End.
阅读更多相关文章推荐
- JS小技巧:判断数据类型的一种方法
- js中判断数据类型对的几种方法
- 判断js中各种数据的类型方法之typeof与0bject.prototype.toString讲解
- JS中判断数据类型的几种方法
- 判断js对象的数据类型,有没有一个最完美的方法?
- 判断js中各种数据的类型方法之typeof与0bject.prototype.toString讲解
- js判断操作系统、判断浏览器类型、判断数据类型权威方法--extjs源码
- js中判断数据类型的方法 typeof
- js 判断数据类型的几种方法
- js 判断各种数据类型的简单方法
- JS判断数据类型检查的方法
- js基本数据类型及判断方法
- JS判断数据类型的三种方法
- js数据类型的判断方法
- 如何判断js中的数据类型:typeof、instanceof、 constructor、 prototype方法比较
- js基本数据类型及判断方法
- 判断JS数据类型的几种方法
- 判断js中各种数据的类型方法之typeof与0bject.prototype.toString讲解
- 判断js中的数据类型的几种方法
- js判断数据类型的几种方法及应用场景分析