【轉】javascript Object使用Array的方法


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

Array.prototype.push

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

如果Object使用push會怎樣?

看下面代碼, 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 給Object

看下面代碼:obj這貨居然變成數組了?其實不然這可能是調試工具的一些輸出檢查問題。
我們用 instanceof 測試  obj instanceof Array //false

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中。

不過如果直接設置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的方法還能正常工作,實在有些意想不到,可能實際應用遠不止這些。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM