javascript 類陣列
阿新 • • 發佈:2018-12-20
定義:
- 擁有length屬性,其它屬性(索引)為非負整數(物件中的索引會被當做字串來處理,這裡你可以當做是個非負整數串來理解)
- 不具有陣列所具有的方法
ps:這是我參考的定義,實際上,只要有length
屬性,且它的屬性值為number
型別就行了。請圍觀評論。
類陣列示例:
var a = {'1':'gg','2':'love','4':'meimei',length:5};
Array.prototype.join.call(a,'+');//'+gg+love++meimei'
非類陣列示例:
var c = {'1':2};
沒有length
屬性,所以就不是類陣列。
javascript中常見的類陣列有arguments
物件和DOM方法的返回結果。
比如 document.getElementsByTagName()
。
類陣列判斷
《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 }
類陣列表現
之所以成為“類陣列”,就是因為和“陣列”類似。不能直接使用陣列方法,但你可以像使用陣列那樣,使用類陣列。
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']:
類陣列物件轉化為陣列
有時候處理類陣列物件的最好方法是將其轉化為陣列。
Array.prototype.slice.call(arguments)
然後就可以直接使用陣列方法啦。
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
來實現。
// 偽陣列轉化成陣列 var makeArray = function(obj) { if (!obj || obj.length === 0) { return []; } // 非偽類物件,直接返回最好 if (!obj.length) { return obj; } // 針對IE8以前 DOM的COM實現 try { return [].slice.call(obj); } catch (e) { var i = 0, j = obj.length, res = []; for (; i < j; i++) { res.push(obj[i]); } return res; } };