gpt4 book ai didi

javascript - 为什么 push 方法适用于 jQuery 对象?

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:50:52 26 4
gpt4 key购买 nike

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

请注意,您的自定义构造函数实例的行为与实际数组不同。


编辑:

关于您问题中的编辑,.push().add() 不同。

.push() 方法用于将 DOM 元素添加到现有的 jQuery 对象。

.add() 方法可以接受一个 DOM 元素,或另一个具有 1 个或多个 DOM 元素的 jQuery 对象,并返回一个 jQuery 对象,其中包含新的添加的元素。

它更像是一个.concat()

关于javascript - 为什么 push 方法适用于 jQuery 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6867483/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com