有时候我们会遇到这种场景,后台给过来的数据是json格式,key还是有序的,然后前端使用常规的for in 循环遍历json,结果显示的顺序和给过来的顺序不一致,这是为什么呢?怎么解决呢?(本文由www.liuyanla.com网站原创)
这是因为json数据是无序的键值对,而数组是有序的,所以要想有序的显示,则要将json的键值对转换为array数组,然后遍历数组,结果既是有序的。
接下来我们说说如何将json数据转换成array数据:
let jsons={ a:”aaa1″, b:”bbb2″, c:”ccc3″, d:”ddd4″, }; let arr=[]; Object.keys(jsons).forEach((key,index)=>{ arr.push(jsons[key]); }); console.log(arr) // (4) [“aaa1”, “bbb2”, “ccc3”, “ddd4”]

以上就是JS 遍历 json对象顺序错乱的原因以及解决方案,完美解决,哈哈
你这有问题啊
什么问题呢,一起讨论一下
arr还是有部分是无序的
可以加我微信,我们探讨一下
CrBHuJkLt
xtrGuIYCk
Its like you read my mind! You appear to know so much approximately this, like you wrote the ebook in it or something.
I feel that you just could do with a few xx to pressure the message house a bit, but other
than that, this is wonderful blog. An excellent read. I will definitely be back.