[英]create array in reverse order
I've got buttons with a common class ( buttons
). 我有一个具有共同类的
buttons
( buttons
)。 How can I add their ID
s in to an array in a reverse order? 如何以相反的顺序将其
ID
添加到数组中?
var yourArray = [];
$('.buttons').each(function() {
yourArray.push( $(this).prop('id') );
});
You could create the array by adding each element to the beginning of the array using unshift()
: 您可以使用
unshift()
将每个元素添加到数组的开头来创建数组:
var yourArray = [];
$('.buttons').each(function() {
yourArray.unshift(this.id);
});
Alternatively you can create it in the current order and then reverse()
it. 或者,您可以按当前顺序创建它,然后将它
reverse()
。 Also note that you can use map()
to create the array initially: 还要注意,您可以使用
map()
最初创建数组:
var yourArray = $('.buttons').map(function() {
return this.id;
}).get().reverse();
Finally you can use this.id
instead of creating a jQuery object just to access a property already accessible without the need of object creation. 最后,您可以使用
this.id
而不是创建jQuery对象,而仅用于访问无需对象创建即可访问的属性。
You can do something simple with map()
and reverse()
您可以使用
map()
和reverse()
做一些简单的事情
var yourArray = $('.buttons').map(function() { return this.id; // get the id }) .get() // get the array .reverse(); // reverse the array console.log(yourArray);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <button id="a" class="buttons"></button> <button id="b" class="buttons"></button>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.