首页 > 编程语言 > 详细

js 判断是否是数组 及原生toString()方法判断数据类型

时间:2020-03-08 23:25:45      阅读:96      评论:0      收藏:0      [点我收藏+]

Array.isArray()

let a = [1,2,3]
Array.isArray(a);//true
此方法为 ES5新增方法 ,兼容Es5之外不支持的问题
if (!Array.isArray) {
  Array.isArray = function(arg) {
    return Object.prototype.toString.call(arg) === ‘[object Array]‘;
  };
}
Object.prototype.toString.call()判断数据类型

1.判断基本类型:

Object.prototype.toString.call(null);//”[object Null]”
Object.prototype.toString.call(undefined);//”[object Undefined]”
Object.prototype.toString.call(“abc”);//”[object String]”
Object.prototype.toString.call(123);//”[object Number]”
Object.prototype.toString.call(true);//”[object Boolean]”

2.判断原生引用类型:

函数类型
Function fn(){console.log(“test”);}
Object.prototype.toString.call(fn);//”[object Function]”
日期类型
var date = new Date();
Object.prototype.toString.call(date);//”[object Date]”
数组类型
var arr = [1,2,3];
Object.prototype.toString.call(arr);//”[object Array]”
正则表达式
var reg = /[hbc]at/gi;
Object.prototype.toString.call(arr);//”[object RegExp]”
自定义类型
function Person(name, age) {
    this.name = name;
    this.age = age;
}
var person = new Person("Rose", 18);
Object.prototype.toString.call(person); //”[object Object]”
很明显这种方法不能准确判断person是Person类的实例,而只能用instanceof 操作符来进行判断,如下所示:
console.log(person instanceof Person);//输出结果为true

3.判断原生JSON对象:

var isNativeJSON = window.JSON && Object.prototype.toString.call(JSON);
console.log(isNativeJSON);//输出结果为”[object JSON]”说明JSON是原生的,否则不是

原文作者:keepup~
原文
地址:https://www.cnblogs.com/cn-chy-com/p/11524980.html

js 判断是否是数组 及原生toString()方法判断数据类型

原文:https://www.cnblogs.com/lpp-11-15/p/12445643.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!