js判断复合数据类型的两种方式(typeof不奏效了)

作者:zccst

typeof认为所有的复合数据类型都是"object",没法进一步细分,所以还得用其他方法

先上结论:

1,(arr && typeof(arr) === "object" && arr.constructor === Array)

2,Object.prototype.toString.call(arr);

Js代码   收藏代码
  1. Object.prototype.toString.call([]);  
  2. //"[object Array]"  
  3. Object.prototype.toString.call({});  
  4. //"[object Object]"  



例子:

Js代码   收藏代码
  1. var arr = [];  
  2. arr['name'] = "helios";  
  3. arr['version'] = 'trunk';  
  4. console.log(arr, typeof arr);  
  5. console.dir(arr);//信息比较全面  
  6. $.each(arr, function(key, item){//没有进入循环,是因为length=0  
  7.     console.log(key, item, item[key]);  
  8. });  
  9. console.log( Object.prototype.toString.call(arr) );  
  10. console.log( arr.constructor , arr.constructor === Array);  
  11. console.log(arr && typeof(arr) === "object" && arr.constructor === Array);  



打印:
[name: "helios", version: "trunk"] "object"
Array[0]
  length: 0
  name: "helios"
  version: "trunk"
  __proto__: Array[0]
[object Array]
function Array() { [native code] } true
true

批注:
1,arr还是数组。只不过length=0,同时绑定了两个静态变量。jQuery不循环这类数据。

2,typeof只是用来判断基本数据类型的。复合数据类型typeof判断出都是"object"

3,instanceof也不奏效,因为他们是继承关系。

Js代码   收藏代码
    1. var arr = [];  
    2. arr['name'] = "helios";  
    3. arr['version'] = 'trunk';  
    4. console.log( arr instanceof Array );  //true  
    5. console.log( arr instanceof Object ); //true 

转载于:https://www.cnblogs.com/shsgl/p/4289937.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值