`

新学一招, 判断一个js对象是不是数组

阅读更多

http://blog.360.yahoo.com/blog-TBPekxc1dLNy5DOloPfzVvFIVOWMB0li?p=916
学来一招, 判断一个js对象是不是数组


function isArray(o) {
  return Object.prototype.toString.call(o) === '[object Array]'; 
}


原文如下 :

引用

The Miller Device

The JavaScript language currently does not provide a good way to distinguish between objects and arrays. The typeof operator is broken: It identifies arrays as objects. Comparing a value's constructor property doesn't work because arrays created in a different frame will have a different constructor. There are do-it-yourself tests for arrayness, but they are complicated and unreliable.

Mark Miller of The Google, by closely reading the ECMAScript standard, has discovered a simpler, more reliable test.

Object.prototype.toString.apply(value) === '[object Array]'

分享到:
评论
6 楼 wy1272086709 2014-01-11  

function isArray(o){
return o.constructor.name=='Array';
}


这种判断的方式有问题没????
5 楼 wanggp001 2009-02-14  
===是严格的判等符号,通常用的==是不区分类型的,即1=='1'是返回true,1==='1'返回false。
这是我的理解,请参考!
4 楼 zcfg 2009-01-21  
http://ajaxian.com/archives/isarray-why-is-it-so-bloody-hard-to-get-right 在Ajaxian上看到了 确实好办法
但一直没看到把节点列表转化为数组的便捷办法
3 楼 czwlucky 2009-01-21  
这一招确实好啊,是正解!
function SubArray(){
}
SubArray.prototype = [];
myArray = new SubArray;
alert(myArray instanceof Array)
alert(Object.prototype.toString.apply(myArray));
像这种判断,虽然instanceof Array是true,但它实际上根本就不能当成数组来用。。。
2 楼 dos200 2009-01-15  
=== 是啥意思呢。。望赐教!
1 楼 lijackly 2009-01-13  
引用到自己的blog中!

相关推荐

Global site tag (gtag.js) - Google Analytics