DIV CSS 佈局教程網

 DIV+CSS佈局教程網 >> 網頁腳本 >> JavaScript入門知識 >> 關於JavaScript >> javascript object array方法使用詳解
javascript object array方法使用詳解
編輯:關於JavaScript     
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的方法還能正常工作,實在有些意想不到,可能實際應用遠不止這些。
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved