如何从jQuery集"弹出"或"转移"

cbp*_*cbp 43 jquery

在Javascript中,数组应该有方法popshift.

但是,JQuery对象似乎缺少这些方法:

$('div').shift(); // Error, shift is undefined
$('div').pop(); // Error, pop is undefined
$('div').splice(); // Splice is OK actually
Run Code Online (Sandbox Code Playgroud)

我想知道为什么缺少这些函数 - 毕竟,jquery对象只是一个数组.

在jquery对象上执行pop和shift函数的最简单方法是什么?

use*_*716 40

它们丢失了,因为jQuery对象不是Array.

(function( $ ) {
    $.fn.pop = function() {
        var top = this.get(-1);
        this.splice(this.length-1,1);
        return top;
    };

    $.fn.shift = function() {
        var bottom = this.get(0);
        this.splice(0,1);
        return bottom;
    };
})( jQuery );
Run Code Online (Sandbox Code Playgroud)

编辑: .slice()不修改原始对象.固定使用.splice()而不是.

  • OMG只使用`$ .fn.pop = Array.prototype.pop` (2认同)

rya*_*nve 11

你最安全的赌注是使用:

[].pop.call($('div'))
[].shift.call($('div'))
Run Code Online (Sandbox Code Playgroud)

如果您想在示例中使用确切的语法,可以增加jQuery.fn:

jQuery.fn.pop = [].pop;
jQuery.fn.shift = [].shift;
Run Code Online (Sandbox Code Playgroud)

后者适用于mutator方法.它也适用于访问器迭代方法,但是请注意,其中许多返回一个你必须重新包装的纯数组.请注意,jQuery有自己的一些版本(例如.map,.slice,.filter等),您可能不想覆盖它们.


BM-*_*BM- 5

这似乎对我有用:

var divArray = $('div').toArray();
var elem = $( divArray.shift() );
Run Code Online (Sandbox Code Playgroud)

.toArray()将 DOM 元素作为 JavaScript 数组返回,可以按预期使用。然后你需要做的就是将它转换回一个 jQuery 对象。