简体   繁体   English

jQuery Object 中的反向迭代?

[英]Reverse iteration in a jQuery Object?

 var   test_data =  {'hr' : [1, 'Hour'], 'min' : [60, 'Minute'], 's' : [3600, 'Second']}

Now while I iterate, I want to get 's' first-现在,当我迭代时,我想先得到 's' -

$.each(test_data, function(i, j) {
         // I need to get 's' first
});

I have tried test_data.revers() which does not work.我尝试过test_data.revers()不起作用。 Any solution?有什么解决办法吗?

You can use Object.keys and .reverse as follows:您可以使用Object.keys.reverse如下:

 var test_data = { 'hr': [1, 'Hour'], 'min': [60, 'Minute'], 's': [3600, 'Second'] }; $.each(Object.keys(test_data).reverse(), function(i, key) { console.log(key, test_data[key]); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

For a defined order, you could sort the keys of the object and iterate them in descending order of the first value of the array.对于定义的顺序,您可以对 object 的键进行排序,并按数组第一个值的降序对其进行迭代。

 var data = { hr: [1, 'Hour'], min: [60, 'Minute'], s: [3600, 'Second'] }; for (const key of Object.keys(data).sort((a, b) => data[b][0] - data[a][0])) { console.log(key, ...data[key]); }

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

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