0
var _txtString = ":un:-:un:-:deux:-:deux:-:deux:-:trois:-:trois:" ;
var _array = ["un", "deux", "trois"]  ;
var _items = new Array();

for (var t =0; t < _array.length; t++) {
    found = _txtString.match(new RegExp(':' + _array[t]+ ':', 'g'));
    _items[t] = parseInt(found.length);
    //_items.sort();
    document.write("<br />" + _items[t] + "  " + _array[t]);
}

嗨,当我运行此代码时,显示的结果会正确计算:

2 un
3 deux
2 trois

但是当我取消注释 sort() 行时,计数是错误的:

2 un
3 deux
3 trois <=

我想要的是对数值返回的结果进行排序。我无法理解的是 sort() 函数会改变实际值?!任何线索为什么?

谢谢

4

2 回答 2

2

因为您正在排序,所以您正在更改数组的顺序。因此,当您对“3”进行排序时,它将成为最后一个索引并将其写出。

_items[t] = parseInt(found.length);  //[2,3,2]
_items.sort();  //[2,2,3]
document.write("<br />" + _items[t] + "  " + _array[t]);  //here you are reading the last index which is 3

如果要按计数排序,则需要在计算完所有内容后进行。

基本思路:

var _txtString = ":un:-:un:-:deux:-:deux:-:deux:-:trois:-:trois:";
var _array = ["un", "deux", "trois"];
var _items = new Array();

for (var t = 0; t < _array.length; t++) {
    found = _txtString.match(new RegExp(':' + _array[t] + ':', 'g'));
    _items.push({
        count: found.length,
        text: _array[t]
    });
}

_items.sort(function (a, b) {
    return a.count - b.count;
});

for (var i = 0; i < _items.length; i++) {
    console.log(_items[i].count, _items[i].text);
}
于 2013-08-01T16:57:49.203 回答
2

javascript 中的 sort 命令执行就地排序,这意味着它将改变您的数组顺序。当这种情况发生时,在我看来,您的代码与您所期望的不同步。

除非您制作数组的副本并对副本进行排序,否则无法避免这种情况,从而使原始数组保持原样。

于 2013-08-01T16:58:21.853 回答