我需要为我的一个项目按JS对关联数组进行排序。我发现此功能在firefox中效果很好,但不幸的是,它在IE8,OPERA,CHROME中不起作用。无法找到使其在其他浏览器中工作的方法,或者找到了适合该功能的其他功能。我真的很感谢您的帮助。
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;
}
最佳答案
这是不可能的。当使用Object
循环遍历其属性时,JavaScript中的for...in
(即您用作“关联数组”的内容)为specified as having no defined order。您可能可以观察到某些浏览器行为之间的一些共同点,但it's not universal。
摘要:如果需要按特定顺序的对象,请使用数组。