[英]Why does the push method work on a jQuery object?
var test = $();
test.push( $('div')[0] );
這有效。 知道為什么嗎? 由於push是一種數組方法,我不明白為什么這種情況適用於這種情況,任何想法?
它是否有實際用途,因為你可以使用.add()?
他們從Array.prototype
借用.push()
。
https://github.com/jquery/jquery/blob/1.6.2/src/core.js#L70
和
https://github.com/jquery/jquery/blob/1.6.2/src/core.js#L296
示例: http : //jsfiddle.net/HgS2R/1/
var MyObj = function(){};
MyObj.prototype.push = Array.prototype.push;
var inst = new MyObj;
inst.push( "test" );
document.write( inst[ 0 ] + '<br>' + inst.length ); // test, 1
請注意,自定義構造函數的實例與實際Array的行為不同。
編輯:
關於你的問題中的編輯, .push()
與.add()
。
.push()
方法用於將DOM元素添加到現有jQuery對象。
.add()
方法可以接受DOM元素或具有1個或多個DOM元素的另一個jQuery對象,並返回添加了新元素的新 jQuery對象。
它更像是一個.concat()
。
我檢查了源代碼並找到了這些代碼塊(帶注釋)。 不確定他們是否回答了你的問題:
// Save a reference to some core methods
toString = Object.prototype.toString,
hasOwn = Object.prototype.hasOwnProperty,
push = Array.prototype.push,
slice = Array.prototype.slice,
trim = String.prototype.trim,
indexOf = Array.prototype.indexOf,
// For internal use only.
// Behaves like an Array's method, not like a jQuery method.
push: push,
sort: [].sort,
splice: [].splice
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.