开发者

How to 'pop' or 'shift' from jQuery set

In Javascript, arrays should have methods pop and shift.

However, JQuery objects seem to be missing these methods:

$('div').shift(); // Error, shift is undefined
$('div').pop(); // Error, pop is undefined
$('div').splice(); // Splice is OK actually

I wonder why these functi开发者_运维知识库ons are missing - after all, the jquery object is just an array.

What's the easiest way of performing pop and shift functions on jquery objects?


They're missing because a jQuery object isn't an 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 );

EDIT: .slice() doesn't modify the original object. Fixed to use .splice() instead.


Your safest bet would be to just use:

[].pop.call($('div'))
[].shift.call($('div'))

If you want to use the exact syntax in your example you can augment jQuery.fn:

jQuery.fn.pop = [].pop;
jQuery.fn.shift = [].shift;

The latter works well for the mutator methods. It'll work for the accessor and iteration methods too, but be advised that many of those returns a pure array that you'd have to rewrap. Be aware that jQuery has is own version of some of these (e.g. .map, .slice, .filter, etc.) that you probably don't want to overwrite.


This seemed to work for me:

var divArray = $('div').toArray();
var elem = $( divArray.shift() );

.toArray() return the DOM elements as a JavaScript Array, which can be used as intended. Then all you need to do is convert it back into a jQuery object.


I realize this answer has already been selected, but here's another alternative that isn't too hard to remember, in case you don't want to worry about having to install plugins all the time.

$('div > :first').detach(); // shift
$('div > :last').detach();  // pop

By the way, I realize there are performance issues with using :last selector as part of your primary selector so you may want to consider doing something like this for pop:

$('div').children(':last').detach();


var $firstDiv = $( $('div').splice(0, 1) );


Another way using jQuery 1.9.1+:

$('div').first().remove();  
$('div').last().remove();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜