【问题标题】:Unwanted sorting of array不需要的数组排序
【发布时间】:2013-10-15 14:39:27
【问题描述】:

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

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>

Here is my jsFiddle example(检查控制台的结果)。它给了我['AAA','BBB','CCC'],而不是所需的['AAA','CCC','BBB']

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

【问题讨论】:

  • 为我工作 Chrome v30 [AAA: "someValue", CCC: "someValue", BBB: "someValue"] (index):29
  • 您在标题中谈论的是.push(),但该方法甚至没有出现在您的代码中。
  • @CBroe:正确,我的错。我已经搞砸了一段时间,我不知道在做什么。工作日在这里结束

标签: javascript jquery arrays sorting


【解决方案1】:

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

你会使用一个数组:

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;

【讨论】:

  • 完美,正是我想要的。我使用了第二种方法,因为这样我就可以毫无问题地进行递归
【解决方案2】:

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

【讨论】:

  • var GatheredIds = [] 如何创建对象而不是数组?
  • @ScottMermelstein,数组总是有索引,而不是属性名。
  • @GurpreetSingh 那么您和 VisioN 的意思是 GatheredIds 是一个数组,但是由于代码使用像 GatheredIds["AAA"] = 'someValue' 这样的语法,所以它们被保存为对象属性而不是数组元素?
  • @ScottMermelstein:没错。
  • @Martijn 谢谢! 更原生的 JS 是什么意思?我刚刚使用了 jQuery 的全部功能,它使代码更短,更少面向临时变量。
猜你喜欢
  • 1970-01-01
  • 2014-10-02
  • 2021-01-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-29
  • 1970-01-01
相关资源
最近更新 更多