jQuery.每个返回索引数组

jQuery.each return indexed array

本文关键字:索引 数组 返回 jQuery      更新时间:2023-09-26

我有这样的代码:

function gatherFollowers() {
            var followers = [];
            jQuery('.follower').each(function(index, value) {
                var i = parseInt(jQuery(this).attr('data-id'));
                followers.push(i);
            });
            return followers;
        }

应该获取所有属性,但结果是:

[100, 99, 88, 72, 63, 34, 31, 30, 29, each: function, eachSlice: function, all: function, any: function, collect: function…]

我怎样才能使它像这样返回一个简单的数组呢?

[4,29,30,31,32,34,36,37,60,61,63,72,76,77,88,99,100] 

谢谢

我相信你可以使用map()来获得你需要的-和。get()

function gatherFollowers() {
    return jQuery('.follower').map(function(i,v){
        return $(v).data('id');
    }).get();
}

小提琴

Try with

function gatherFollowers() {
    var followers = $.map($('.follower'), function(value) {
        return parseInt($(this).data('id'), 10);
    });
    // followers should be an array of numbers
}

我已经改变了你的代码使用$.map,也使用.data()访问HTML 5数据- id属性。

实际上,将这个函数结果推入对象确实帮助了我followers.data = gatherFollowers();

现在console.log显示

Object {data: Array[9], type: "custom"}
data: Array[9]
0: "100"
1: "99"
2: "88"
3: "72"
4: "63"
5: "34"
6: "31"
7: "30"
8: "29"
length: 9
__proto__: Array[0]
type: "custom"

我试过了:

//HTML
//<div id="1" class="follower">follower1</div>
//<div id="2" class="follower">follower2</div>
var followers = [];
$('.follower').each( function(index, value){
    var follower_id = $('.follower:eq(' + index + ')').attr('id');
    followers.push(follower_id)
});
console.log(followers)
//output [1,2]