原文:http://www.javashuo.com/article/p-pojgutlf-x.htmljavascript
定义:java
var a = {'1':'gg','2':'love','4':'meimei',length:5}; Array.prototype.join.call(a,'+');//'+gg+love++meimei'
var c = {'1':2};
没有length
属性,因此就不是类数组。node
javascript中常见的类数组有arguments
对象和DOM方法的返回结果。
好比 document.getElementsByTagName()
。segmentfault
《javascript权威指南》上给出了代码用来判断一个对象是否属于“类数组”。以下:数组
// Determine if o is an array-like object. // Strings and functions have numeric length properties, but are // excluded by the typeof test. In client-side JavaScript, DOM text // nodes have a numeric length property, and may need to be excluded // with an additional o.nodeType != 3 test. function isArrayLike(o) { if (o && // o is not null, undefined, etc. typeof o === 'object' && // o is an object isFinite(o.length) && // o.length is a finite number o.length >= 0 && // o.length is non-negative o.length===Math.floor(o.length) && // o.length is an integer o.length < 4294967296) // o.length < 2^32 return true; // Then o is array-like else return false; // Otherwise it is not }
之因此成为“类数组”,就是由于和“数组”相似。不能直接使用数组方法,但你能够像使用数组那样,使用类数组。ide
var a = {'0':'a', '1':'b', '2':'c', length:3}; // An array-like object Array.prototype.join.call(a, '+''); // => 'a+b+c' Array.prototype.slice.call(a, 0); // => ['a','b','c']: true array copy Array.prototype.map.call(a, function(x) { return x.toUpperCase(); }); // => ['A','B','C']:
有时候处理类数组对象的最好方法是将其转化为数组。spa
Array.prototype.slice.call(arguments)
而后就能够直接使用数组方法啦。prototype
var a = {'0':1,'1':2,'2':3,length:3}; var arr = Array.prototype.slice.call(a);//arr=[1,2,3]
对于IE9之前的版本(DOM实现基于COM),咱们能够使用makeArray
来实现。code