##数据场景 在处理类似这样的Json对象时: ```json { "AED": "United Arab Emirates Dirham", "AFN": "Afghan Afghani", "ALL": "Albanian Lek", "AMD": "Armenian Dram", "ANG": "Netherlands Antillean Guilder", "AOA": "Angolan Kwanza", "ARS": "Argentine Peso", "AUD": "Australian Dollar", "BSD": "Bahamian Dollar", "BTC": "Bitcoin", "BTN": "Bhutanese Ngultrum", "CNH": "Chinese Yuan (Offshore)", "CNY": "Chinese Yuan", "COP": "Colombian Peso", "CRC": "Costa Rican Colón", "CUC": "Cuban Convertible Peso", "CUP": "Cuban Peso", "CVE": "Cape Verdean Escudo", "CZK": "Czech Republic Koruna", "DJF": "Djiboutian Franc", "DKK": "Danish Krone", "JEP": "Jersey Pound", "JMD": "Jamaican Dollar", "JOD": "Jordanian Dinar", "JPY": "Japanese Yen", "KES": "Kenyan Shilling", "KGS": "Kyrgystani Som", "KHR": "Cambodian Riel", "KMF": "Comorian Franc", "KPW": "North Korean Won", "MWK": "Malawian Kwacha", "MXN": "Mexican Peso", "MYR": "Malaysian Ringgit", "MZN": "Mozambican Metical", "NAD": "Namibian Dollar", "NGN": "Nigerian Naira", "NIO": "Nicaraguan Córdoba", "NOK": "Norwegian Krone", "NPR": "Nepalese Rupee", "NZD": "New Zealand Dollar", "OMR": "Omani Rial" } ``` 可见key已经是有序的了,然后在JavaScript中使用常规的forin去遍历,结果显示的顺序和给过来的顺序不一致。 ##原因 这是因为Json数据是无序的键值对,而数组是有序的,直接forin遍历肯定就是无序的。 ##解决方法 先将Json对象转为map对象,使用map对象sort方法进行按key值排序,然后再转为数据或者直接遍历处理,结果才是有序的。 ** 这里截取我在傻妞插件中使用的方法来说明 ** ```javascript //data为接收到的Json对象 data={"keys":"values"}; //每次返回均为有序 let stringMap = new Map(); for (const key in data) { stringMap.set(key, data[key]); } countryList = Array.from(stringMap).sort((a, b) => { return a[0].localeCompare(b[0]) }) countryList.forEach(v => { Debug(v) }) //每次返回均为无序 let index=1; for (key in data) { if (index % 45 == 0) { msgString = msgString.join("\n"); sendText(msgString); msgString = []; } msgString.push(index + ". (" + key + ") - " + data[key]); index++; } ``` Last modification:January 28, 2022 © Allow specification reprint Support Appreciate the author AliPayWeChat Like 0 If you think my article is useful to you, please feel free to appreciate
One comment
2025年10月新盘 做第一批吃螃蟹的人coinsrore.com
新车新盘 嘎嘎稳 嘎嘎靠谱coinsrore.com
新车首发,新的一年,只带想赚米的人coinsrore.com
新盘 上车集合 留下 我要发发 立马进裙coinsrore.com
做了几十年的项目 我总结了最好的一个盘(纯干货)coinsrore.com
新车上路,只带前10个人coinsrore.com
新盘首开 新盘首开 征召客户!!!coinsrore.com
新项目准备上线,寻找志同道合的合作伙伴coinsrore.com
新车即将上线 真正的项目,期待你的参与coinsrore.com
新盘新项目,不再等待,现在就是最佳上车机会!coinsrore.com
新盘新盘 这个月刚上新盘 新车第一个吃螃蟹!coinsrore.com