如何排序在Javascript关联数组? [英] How to sort associative array in Javascript?

查看:253
本文介绍了如何排序在Javascript关联数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要为我的项目之一排序JS关联数组。我发现这个功能,在Firefox的伟大工程,但不幸的是它在IE8,歌剧,铬不工作...不能找到使它在其他浏览器,或发现,将适合的目的另一个函数的方式。我真的AP preciate任何帮助。

 函数sortAssoc(aInput)
{
    变种aTemp = [];
    对(在aInput变种SKEY)aTemp.push([SKEY,aInput [SKEY]。长度]);
    aTemp.sort(函数(){返回参数[0] [1];参数[1] [1]});
    VAR aOutput =新的对象();
    //对于(变量参数nIndex = aTemp.length-1;参数nIndex> = 0; nIndex--)
    为(变量参数nIndex = 0;参数nIndex&下; = aTemp.length-1;参数nIndex ++)
        aOutput [aTemp [参数nIndex] [0]] = aInput [aTemp [参数nIndex] [0];
    // aOutput [aTemp [参数nIndex] [0]] = aTemp [参数nIndex] [1];
    返回aOutput;
}


解决方案

这是不可能的。一个对象在JavaScript中(这是你用什么作为你的关联数组)是的使用为中... 遍历其属性进行遍历时,指定为具有没有定义订单。您可以观察到一些浏览器的行为之间有一些共同点,但它不是万能

摘要:如果你在一个特定的顺序需要的对象,使用数组

I need to sort associative array by JS for one of my projects. I found this function, that works great in firefox, but unfortunately it doesnt work in IE8, OPERA, CHROME... Cant find the way to make it work in other browsers, or find another function that would fit the purpose. I really appreciate any help.

function sortAssoc(aInput)
{
    var aTemp = [];
    for (var sKey in aInput) aTemp.push([sKey, aInput[sKey].length]);
    aTemp.sort(function () {return arguments[0][1] < arguments[1][1]});
    var aOutput = new Object();
    //for (var nIndex = aTemp.length-1; nIndex >=0; nIndex--)
    for (var nIndex = 0; nIndex <= aTemp.length-1; nIndex++)
        aOutput[aTemp[nIndex][0]] = aInput[aTemp[nIndex][0]];
    //aOutput[aTemp[nIndex][0]] = aTemp[nIndex][1];
    return aOutput;
}

解决方案

This is impossible. An Object in JavaScript (which is what you're using as your "associative array") is specified as having no defined order when iterating over its properties using a for...in loop. You may be able to observe some common ground between some browsers' behaviour, but it's not universal.

Summary: if you need objects in a specific order, use an array.

这篇关于如何排序在Javascript关联数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆