[英]Object iteration in reverse (javascript)
How can I iterate over a javascript object, from back to front. 如何从头到尾遍历javascript对象。
The object looks like this. 对象看起来像这样。
{"33":140, "34":100, "35":120, "36":200}
I want it to display like this... 我希望它像这样显示...
36 | 200
35 | 120
34 | 100
33 | 140
I tried sorting first then displaying, but it sorts by the second number, not the key. 我尝试先排序然后显示,但它是按第二个数字而不是键进行排序。 How would I either iterate from back to front, or reverse sort based on the key.
我将如何从后到前进行迭代,或者基于密钥进行反向排序。
I realize this is pretty simple, but Im getting pretty frustrated with it.... 我意识到这很简单,但是我对此感到非常沮丧。
A fairly modern version would look like this: 一个相当现代的版本如下所示:
Object.keys(obj).sort(function (a, b) {
return Number(b) - Number(a);
}).forEach(function (current) {
console.log(current + ' | ' + obj[current]);
});
Similarly, but with a little bit more code, it could be written for older browsers, too. 同样,但是只要多一点代码,它也可以为较旧的浏览器编写。 Or you use shims.
或者您使用垫片。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.