jQuery.each:重新排序数组
我最近一直在摆弄数组和数组排序,并偶然发现了一些奇怪的东西。
考虑这种情况:
arr = {};
arr[1] = "one";
arr[2] = "two";
arr[105] = "three";
arr[4] = "four";
$.each(arr, function (key, val) {
$(body).html(key + " => " + val);
});
现在,我们应该希望得到以下结果:
1 => one
2 => two
105 => three
4 => four
对吗?不幸的是没有。我收到数字排序,导致索引 105
成为序列中的最后一项。有人知道我如何克服这个问题吗?非常感谢您的指导,谢谢。
I've been fiddling around with arrays and array ordering recently and stumbled across something peculiar.
Take this situation:
arr = {};
arr[1] = "one";
arr[2] = "two";
arr[105] = "three";
arr[4] = "four";
$.each(arr, function (key, val) {
$(body).html(key + " => " + val);
});
Now, we should hope for the following results:
1 => one
2 => two
105 => three
4 => four
Right? Unfortunately not. I am receiving a numeric sorting which results in index 105
being the last item in the sequence. Anybody have an idea of how I can overcome this problem? Words of guidance are very much appreciated, thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
那不是一个数组。它是一个对象。因此,没有保证订单。
为了保证某种序列,您可以在数组中定义序列,然后迭代该数组,从对象中选择每个数组值的索引。
That's not an Array. It's an Object. And as such, there is no guaranteed order.
To guarantee some sort of sequence, you could define the sequence in an Array, then iterate that Array, selecting the index of each array value from the object.
也许你可以尝试这个:
Maybe you could try this instead: