我有这段代码:
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]
由于
答案 0 :(得分:4)
我确信你可以使用map()来获得你需要的东西 - 和.get()
function gatherFollowers() {
return jQuery('.follower').map(function(i,v){
return $(v).data('id');
}).get();
}
答案 1 :(得分:1)
尝试
function gatherFollowers() {
var followers = $.map($('.follower'), function(value) {
return parseInt($(this).data('id'), 10);
});
// followers should be an array of numbers
}
答案 2 :(得分:0)
嗯,实际上将这个函数结果推入对象确实对我有帮助
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"
正如所料。
答案 3 :(得分:0)
我试过了:
//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]