最新文章专题视频专题问答1问答10问答100问答1000问答2000关键字专题1关键字专题50关键字专题500关键字专题1500TAG最新视频文章推荐1 推荐3 推荐5 推荐7 推荐9 推荐11 推荐13 推荐15 推荐17 推荐19 推荐21 推荐23 推荐25 推荐27 推荐29 推荐31 推荐33 推荐35 推荐37视频文章20视频文章30视频文章40视频文章50视频文章60 视频文章70视频文章80视频文章90视频文章100视频文章120视频文章140 视频2关键字专题关键字专题tag2tag3文章专题文章专题2文章索引1文章索引2文章索引3文章索引4文章索引5123456789101112131415文章专题3
当前位置: 首页 - 科技 - 知识百科 - 正文

js中类型检测的四种方法介绍(代码)

来源:动视网 责编:小采 时间:2020-11-27 19:32:17
文档

js中类型检测的四种方法介绍(代码)

js中类型检测的四种方法介绍(代码):本篇文章给大家带来的内容是关于js中类型检测的四种方法介绍(代码),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。从最垃圾的方式到最牛逼的方式依次排列为:typeof --> constructor --> instanceof --> to
推荐度:
导读js中类型检测的四种方法介绍(代码):本篇文章给大家带来的内容是关于js中类型检测的四种方法介绍(代码),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。从最垃圾的方式到最牛逼的方式依次排列为:typeof --> constructor --> instanceof --> to


本篇文章给大家带来的内容是关于js中类型检测的四种方法介绍(代码),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。

从最垃圾的方式到最牛逼的方式依次排列为:typeof --> constructor --> instanceof --> toString

1.typeof

检测对象类型太过模糊,function、object、array类型都会返回object,所以此方法垃圾,但实用性很强,气场很强大

2.constructor

实例对象的构造函数 (实例对象.constructor),返回构造函数,可以分辨出类型

var str = 'abc';
 var num = 100;
 var arr = new Array();
 var date = new Date();
 alert(str.constructor);
 alert(num.constructor);
 alert(arr.constructor);
 alert(date.constructor);

3.instanceof

判断一个对象是否是一个构造函数(类)的实例。注意此方法只能检测实例对象。返回布尔值

 var str=new String('abc');
 var num=new Number(100);
 var arr=new Array();
 var date=new Date();
 alert(str instanceof String);
 alert(num instanceof Number);
 alert(arr instanceof Array);
 alert(date instanceof Date);
 alert(str instanceof Object);

4.toString()

最牛逼的五星级方法,此方法功能强大,既可以进制转换,又可以转字符串,使用起来逼格级高

 console.log(Object.prototype.toString.call(5).slice(8,-1));
 console.log(Object.prototype.toString.call('abc').slice(8,-1));
 console.log(Object.prototype.toString.call(true).slice(8,-1));
 console.log(Object.prototype.toString.call(function(){}).slice(8,-1));
 console.log(Object.prototype.toString.call([]).slice(8,-1));
 console.log(Object.prototype.toString.call({}).slice(8,-1));
 console.log(Object.prototype.toString.call(/\d/g).slice(8,-1));
 console.log(Object.prototype.toString.call(new Date).slice(8,-1));
 console.log(Object.prototype.toString.call(null).slice(8,-1));
 console.log(Object.prototype.toString.call(undefined).slice(8,-1));
 console.log(Object.prototype.toString.call(Math).slice(8,-1));
 // Number
 // String
 // Boolean
 // Function
 // Array
 // Object
 // RegExp
 // Date
 // Null
 // Undefined
 // Math

相关推荐:

js数据类型检测的4种方法

Javascript isArray 数组类型检测函数_javascript技巧

JavaScript中对数据类型检测的方法总结

文档

js中类型检测的四种方法介绍(代码)

js中类型检测的四种方法介绍(代码):本篇文章给大家带来的内容是关于js中类型检测的四种方法介绍(代码),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。从最垃圾的方式到最牛逼的方式依次排列为:typeof --> constructor --> instanceof --> to
推荐度:
标签: 介绍 检测 js
  • 热门焦点

最新推荐

猜你喜欢

热门推荐

专题
Top