国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 語言 > JavaScript > 正文

javascript object array方法使用詳解

2024-05-06 14:20:44
字體:
來源:轉載
供稿:網友
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的方法還能正常工作,實在有些意想不到,可能實際應用遠不止這些。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表

圖片精選

主站蜘蛛池模板: 丹江口市| 淮北市| 长汀县| 宁化县| 河源市| 五指山市| 德昌县| 五原县| 麦盖提县| 随州市| 留坝县| 娱乐| 中江县| 内乡县| 郓城县| 德惠市| 凉城县| 哈密市| 毕节市| 浦东新区| 包头市| 正宁县| 上高县| 阳城县| 砚山县| 平泉县| 寿宁县| 甘孜县| 北川| 周宁县| 新干县| 湖口县| 黑龙江省| 大港区| 兴海县| 安西县| 洞口县| 通渭县| 边坝县| 盖州市| 东海县|