为什么.sort()产生我的输出?

时间:2017-04-28 23:52:03

标签: javascript sorting

我有给定的数组

[ [ [ 'One' ], [ 'First', 'Fourth', 'Third' ] ],
  [ [ 'Three' ], [ 'First', 'Third' ] ],
  [ [ 'Two' ], [ 'First', 'Second', 'Third' ] ],
  [ [ 'One three' ], [ 'Fourth', 'Third' ] ],
  [ [ 'One two' ], [ 'Fourth', 'Second', 'Third' ] ],
  [ [ 'One two three' ], [ 'Second', 'Third' ] ] ]

我希望在javascript中按顺序对其进行排序:

[[["One"],["First","Fourth","Third"]], 
 [["One three"],["Fourth","Third"]], 
 [["One two"],["Fourth","Second","Third"]], 
 [["One two three"],["Second","Third"]], 
 [["Three"],["First","Third"]], 
 [["Two"],["First","Second","Third"]]]

我的信念是,一个简单的.sort()调用就可以了。查看w3schools documentation on .sort(),它说

  

默认情况下,sort()方法将值排序为字符串   按字母顺序排列。

因此,我认为持有子子阵列['One']的子阵列将位于顶部。

然而,我的输出结果是:

[[["One three"],["Fourth","Third"]], 
 [["One two three"],["Second","Third"]], 
 [["One two"],["Fourth","Second","Third"]], 
 [["One"],["First","Fourth","Third"]], 
 [["Three"],["First","Third"]], 
 [["Two"],["First","Second","Third"]]]

为什么会这样?为什么[“One”]排在第4位而不是之前的3位?我不知道如何通过词典编纂推理。我甚至在控制台中检查了["One"] < ["One three"]并返回true

我熟悉将自定义排序函数作为可选参数传递给.sort()函数的技巧,但我的期望是没有必要。希望得到一个解释,并且可能需要指导哪些自定义排序功能是合适的。

更新: 根据下面的有用评论,我现在看到我原来的直觉是错误的。将以下函数传递给.sort()就可以了。

function sortFunction(a, b){
  if (a[0] < b[0]){
    return -1;
  } else if (a[0] > b[0]){
    return 1;
  } else {
    return 0;
  }
}

0 个答案:

没有答案