2

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

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']

重要的!这必须递归。现在不是简化问题。

4

2 回答 2

4

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

使用数组,您将使用:

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;
于 2013-10-15T14:45:35.430 回答
3

发生这种情况是因为您将标题存储为对象属性。在您的示例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/

于 2013-10-15T14:41:50.417 回答