不需要的数组排序

Unwanted sorting of array

本文关键字:数组排序 不需要      更新时间:2023-09-26

我有以下代码来获取元素的顺序。但是,它不是按元素顺序获取数组,而是按字母顺序排列。

function gatherTreeIds( $parent ){
    var GatheredIds = [];
    $parent.children('div.nt_row').each(function(){
        GatheredIds[ this.title ] = 'someValue';
    });
    return GatheredIds;
}
<div id="Wrap">
    <div class="nt_row" title="AAA"></div>        
    <div class="nt_row" title="CCC"></div>
    <div class="nt_row" title="BBB"></div>
</div>

这是我的jsFiddle示例(检查控制台以获取结果)。它给了我['AAA','BBB','CCC']而不是所需的['AAA','CCC','BBB'].

重要!这必须递归。目前不是简化问题。

你混淆了数组和哈希这两个概念。数组有顺序,而哈希有命名键,你不能在一个数据单一结构中同时具有两者。

对于数组,您将使用:

var GatheredIds = [];
$parent.children('div.nt_row').each(function(){
    GatheredIds.push('someValue');
});
return GatheredIds;

如果要记录项目标题,可以使用哈希数组:

var GatheredIds = [];
$parent.children('div.nt_row').each(function(){
    GatheredIds.push({value: 'someValue', title: this.title);
});
return GatheredIds;

发生这种情况是因为您将标题存储为对象属性。在您的示例中GatheredIds不是数组,这是一个对象。

JavaScript 中的对象没有顺序(与 PHP 的映射数组相反)。如果需要遵循顺序,则应改用数组。

一种可能的解决方案:

function gatherTreeIds( $parent ){
    return $parent.children('div.nt_row').map(function() {
        return {
            title: this.title,
            value: 'someValue'
        };
    }).get();
}

演示:http://jsfiddle.net/FmyBb/4/