jQuery.each:重新排序数组

发布于 2024-11-25 02:32:34 字数 429 浏览 2 评论 0原文

我最近一直在摆弄数组和数组排序,并偶然发现了一些奇怪的东西。

考虑这种情况:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

檐上三寸雪 2024-12-02 02:32:34

那不是一个数组。它是一个对象。因此,没有保证订单。

为了保证某种序列,您可以在数组中定义序列,然后迭代该数组,从对象中选择每个数组值的索引。

arr = {};
arr[1] = "one";
arr[2] = "two";
arr[105] = "three";
arr[4] = "four";

var order = [1,2,105,4];

$.each(order, function(i,val) {
    console.log( val + '=>' + arr[ val ] );
});

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.

arr = {};
arr[1] = "one";
arr[2] = "two";
arr[105] = "three";
arr[4] = "four";

var order = [1,2,105,4];

$.each(order, function(i,val) {
    console.log( val + '=>' + arr[ val ] );
});
失去的东西太少 2024-12-02 02:32:34

也许你可以尝试这个:

arr =
[   ['1', 'one']
,   ['2', 'two']
,   ['105', 'three']
,   ['4', 'four']
];

$.each(arr, function(key, values)
{
    $(body).html(values[0] + " => " + values[1]);
});

Maybe you could try this instead:

arr =
[   ['1', 'one']
,   ['2', 'two']
,   ['105', 'three']
,   ['4', 'four']
];

$.each(arr, function(key, values)
{
    $(body).html(values[0] + " => " + values[1]);
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文