簡體   English   中英

為什么push方法適用於jQuery對象?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM