博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
判断一个对象是不是数组的方法
阅读量:4298 次
发布时间:2019-05-27

本文共 1722 字,大约阅读时间需要 5 分钟。

(1) typeof 无法判断 只能判断原始类型的值和函数

(2)isPrototypeOf 判断父及对象 可检查整个原型链 //可能继承自数组

console.log(Array.prototype.isPrototypeOf([])?"是数组":"不是数组");
console.log(Array.prototype.isPrototypeOf({})?"是数组":"不是数组");
console.log(Array.prototype.isPrototypeOf(function(){})?"是数组":"不是数组");
 

(3)constructor 检查指定对象的构造函数 可检查整个原型链 //可能继承自数组 

var father={};
var son={};
father.__proto__=Array.prototype;
son.__proto__=father;
console.log(son.contructor==Array?"是数组":"不是数组")
console.log({}.contructor==Array?"是数组":"不是数组");
console.log(function(){}.contructor==Array?"是数组":"不是数组");
 

(4)instanceof 检查一个对象是否是制定构造函数的实例 可检查整个原型链 //可能继承自数组

var father={};
var son={};
father.__proto__=Array.prototype;
son.__proto__=father;
console.log(son instanceof Array?"是数组":"不是数组");
console.log({} instanceof Array?"是数组":"不是数组");
console.log(function(){} instanceof Array?"是数组":"不是数组");
 

(5)强行用要检查的对象,调用原始的toString方法 不检查整个原型链 //[object class]: class-Array Date Object //只能检查最初就是数组创建的对象。

console.log(Object.prototype.toString.call([])=="[object Array]"?"是数组":"不是数组");
console.log(Object.prototype.toString.call({}));
console.log(Object.prototype.toString.call(function(){}));
console.log(Object.prototype.toString.call(/\d/));
var father={}; var son={};
father.__proto__=Array.prototype;
son.__proto__=father;
console.log(Object.prototype.toString.call(son)=="[object Array]"?"是数组":"不是数组");//不是 //结论: 对象一旦创建,class属性就无法修改 //修改继承关系,也无法修改class属性

 

(6) Array.isArray(obj) 不检查整个原型链

console.log(Array.isArray([]));
console.log(Array.isArray({}));
//如果浏览器不支持isArray
if(Array.prototype.isArray===undefined){//添加isArray方法
  Array.prototype.isArray=function(arg){//强行调用原始toString方法,和"[object Array]"比较
    return Object.prototype.toString.call(arg) =="[object Array]"?"是数组":"不是数组";
  }
}

转载地址:http://stiws.baihongyu.com/

你可能感兴趣的文章
CTA策略如何过滤部分震荡行情?
查看>>
量化策略回测DualThrust
查看>>
量化策略回测BoolC
查看>>
量化策略回测DCCV2
查看>>
mongodb查询优化
查看>>
五步git操作搞定Github中fork的项目与原作者同步
查看>>
git 删除远程分支
查看>>
删远端分支报错remote refs do not exist或git: refusing to delete the current branch解决方法
查看>>
python multiprocessing遇到Can’t pickle instancemethod问题
查看>>
APP真机测试及发布
查看>>
iOS学习之 plist文件的读写
查看>>
通知机制 (Notifications)
查看>>
10 Things You Need To Know About Cocoa Auto Layout
查看>>
C指针声明解读之左右法则
查看>>
一个异步网络请求的坑:关于NSURLConnection和NSRunLoopCommonModes
查看>>
iOS 如何放大按钮点击热区
查看>>
ios设备唯一标识获取策略
查看>>
获取推送通知的DeviceToken
查看>>
Could not find a storyboard named 'Main' in bundle NSBundle
查看>>
CocoaPods安装和使用教程
查看>>