简体   繁体   English

防止使用Java中的for-in循环进行排序

[英]Prevent sorting with for-in loop in Javascript

I have the following JSON array sorted by type (rather than ID). 我有以下按类型(而非ID)排序的JSON数组。

var response = {"5":"Contacts","2":"Messages","3":"Profiles","1":"Schools","4":"Statistics"};
for (var key in response) {
    alert(key + ' ' + response[key]);
}

I am wanting the order to stay as is however what is happening is that it is sorting it by ID so that it produces "1 Schools" first. 我希望订单保持原样,但是正在发生的事情是按ID对其进行排序,以便它首先生成“ 1所学校”。 How do I prevent a for-in loop from sorting by key? 如何防止for-in循环按键排序?

I realize that no sorting order is guaranteed with a for-in loop, so how do I get around this? 我意识到不能使用for-in循环来保证排序顺序,那么如何解决呢? I need to access both the key and type. 我需要访问密钥和类型。 Is there a different type of array and/or loop that I should be using instead? 我应该使用其他类型的数组和/或循环吗?

Also, just for further clarification and in case it makes a difference, my actual code has the JSON array coming from an AJAX request from PHP using json_encode. 另外,为了进一步说明问题,以防万一,我的实际代码使用来自JSON_encode的PHP AJAX请求提供了JSON数组。

How do I prevent a for-in loop from sorting by key? 如何防止for-in循环按键排序?

You can't. 你不能 The iteration order is unspecified and implementation depended 1 . 迭代顺序未指定,实现取决于1 If you need to traverse your data in a predefined order, use an array instead. 如果需要按预定义的顺序遍历数据,请改用数组。


1: Most popular browsers will iterate over numeric properties in ascending order and then non-numeric properties in insertion order, but again, that's an implementation detail. 1:大多数流行的浏览器将按升序对数字属性进行迭代,然后按插入顺序对非数字属性进行迭代,但这再次是实现细节。

You do not have an array, you have an object. 您没有数组,有一个对象。 Key ordering in an object is not guaranteed in javascript. 使用javascript不能保证对象中的键顺序。 If you want a sorted collection, you should use an actual array: 如果要排序的集合,则应使用实际的数组:

var response = [{"key":"5", "value":"Contacts"},{"key":"2", "value":"Messages"},{"key":"3", "value":"Profiles"},{"key":"1", "value":"Schools"},{"key":"4", "value":"Statistics"}];
for (var i =0; i < response.length; i++) {
    alert(response[i].key + ' ' + response[i].value);
}

If you don't have access to the server but the order of the key is guaranteed you can try the following: 如果您无权访问服务器,但是可以保证密钥的顺序,则可以尝试以下操作:

Map the keys in the order you want them and loop them that way 按照您想要的顺序映射键并以这种方式循环

var response = {"5":"Contacts","2":"Messages","3":"Profiles","1":"Schools","4":"Statistics"};
var map = ["5","2","3","1","4"]; 
for(var i = 0; i < map.length;i++){
    alert(i+' '+response[map[i]])
}

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

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