jQuery.each中的反向对象 [英] Reverse object in jQuery.each

查看:109
本文介绍了jQuery.each中的反向对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

HTML:

<input id="sdata" type="hidden" value='{"1651":["12","1"],"1650":["30","0"],"1649":["20","0"],"1648":["13","2"],"1647":["11","0"],"1646":["10","0"],"1645":["12","0"],"1644":["8","0"],"1643":["16","1"],"1642":["10","1"],"1641":["10","0"],"1640":["18","3"]}' />

JS:

var data = $.parseJSON($('#sdata').val());
$.each(data, function(id, sc) {
    alert(id);
}

OUT:1640,1641,1642,...,1651

OUT: 1640, 1641, 1642, ..., 1651

如何按相反的顺序排列(例如1651, 1650 ...)?

How to make it in reverse order (ex. 1651, 1650...)?

推荐答案

实际上,你不能以任何可靠的方式。因为你在枚举一个对象,从来没有保证订单。

As it is, you can't in any reliable manner. Because you are enumerating an Object, there is never a guaranteed order.

如果你想要一个有保证的数字订单,你需要使用一个数组,然后向后迭代。

If you want a guaranteed numeric order, you would need to use an Array, and iterate backwards.

编辑:这会将您的对象转换为数组,并进行反向迭代。

This will convert your Object to an Array, and do a reverse iteration.

请注意,只有当所有属性都是数字时才会起作用。

Note that it will only work if all the properties are numeric.

var data = $.parseJSON($('#sdata').val());
var arr = [];

for( var name in data ) {
    arr[name] = data[name];
}
var len = arr.length;
while( len-- ) {
    if( arr[len] !== undefined ) {
        console.log(len,arr[len]);
    }
}

这篇关于jQuery.each中的反向对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆