简体   繁体   English

jQuery.each返回索引数组

[英]jQuery.each return indexed array

I have this code: 我有以下代码:

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

That should grab all attributes but in result it returns this: 那应该获取所有属性,但结果将返回以下内容:

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

How could I make it return simple array like this: 我如何使其返回像这样的简单数组:

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

Thanks 谢谢

I'm sure you can use map() to get what you need - and .get() 我确定您可以使用map()获得所需的内容-和.get()

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

FIDDLE 小提琴

Try with 试试看

function gatherFollowers() {
    var followers = $.map($('.follower'), function(value) {
        return parseInt($(this).data('id'), 10);
    });

    // followers should be an array of numbers
}

I've changed your code to use $.map and also to use .data() to access the HTML 5 data- id attribute. 我已将您的代码更改为使用$.map以及使用.data()来访问HTML 5 data- id属性。

Well, in fact pushing this function result into object really helped me followers.data = gatherFollowers(); 好吧,事实上,将此函数结果推送到对象中确实对我的followers.data = gatherFollowers();

Now console.log shows 现在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"

as expected. 如预期的那样。

I tried this: 我尝试了这个:

//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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM