javascript object array方法使用詳解

來源:互聯網
上載者:User

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
1obj.push(1)//返回obj.length
2obj.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個
divjq.length // 40
jq.length = 0;jq// ? jq中仍然存放了40個dom對象 length屬性不會和“數組”項總和對應起來。
Object使用array的方法還能正常工作,實在有些意想不到,可能實際應用遠不止這些。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.