【轉】javascript Object使用Array的方法

原文: http://www.cnblogs.com/idche/archive/2012/03/17/2403894.htmlhtml

Array.prototype.pushjquery

push向數組尾部添加一項並更新length ,返回數組長度。數組

若是Object使用push會怎樣?dom

看下面代碼, obj好像數組同樣工做了。length會自動更新。工具

var push = Array.prototype.push;
var obj = {};
push.call(obj, "hello"); // 返回值 1
// obj {"0":"hello", length:0}
push.call(obj, "world"); // 返回值 2
// obj {"0":"hello", "1":"world",length:2}


Array.prototype.length  Array.prototype.splice測試

把length和splice 給Objectspa

看下面代碼:obj這貨竟然變成數組了?其實否則這多是調試工具的一些輸出檢查問題。
咱們用 instanceof 測試  obj instanceof Array //falseprototype

var obj = {
length:0,
splice:Array.prototype.splice
};
console.log( obj ); // 打印:[]

繼續看下面的代碼:調試

obj.push(0)//返回obj.length  1
obj.push(1)//返回obj.length 2
obj.splice(0, 1);//刪除第一項 返回刪除項[0]
obj.length // 1 splice刪除一項的時候一樣更新 length屬性

這樣obj的表現幾乎和array同樣了。不出意外slice,pop,shift,unshift什麼的均可以正常工做在object中。code

不過若是直接設置length,在數組中會刪除大於length的下表的項, 但裏的obj並不不會更新。

 

應用在哪?
jQuery對象表現像一個array,其實他是一個對象。這種對象如何new出來呢?
實際jQuery把Array的方法借給Object,從而達到這個jQuery對象的效果,jQuery對象內部也直接使用push等Array的方法。

 

看看jQuery的部分源碼 (注意加粗)

複製代碼
// Start with an empty selector
selector: "",

// The current version of jQuery being used
jquery: "1.7.1",

// The default length of a jQuery object is 0
length: 0,
......

// For internal use only.
// Behaves like an Array's method, not like a jQuery method.
push: push,
sort: [].sort,
splice: [].splice
複製代碼

 

若是你要把Object玩成Array,那麼可能潛在的問題length屬性不會和「數組」項總和對應起來。

因此直接使用length設置長度不會獲得支持。

看下面jquery代碼,雖然length更新了,jquery的對象並沒更新。(固然這並非jquery的問題)

var jq = $('div') //假設咱們在頁面獲取了40個div
jq.length // 40
jq.length = 0;
jq// ? jq中仍然存放了40個dom對象 length屬性不會和「數組」項總和對應起來。



Object使用array的方法還能正常工做,實在有些意想不到,可能實際應用遠不止這些。

相關文章
相關標籤/搜索