JavaScript中,排序ARRAY1基于arry2 [英] javascript, sort array1 based on arry2
本文介绍了JavaScript中,排序ARRAY1基于arry2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我没有在JavaScript如下:
I did the following in javascript:
var arr1 =[1,2,3,4];
var arr2 =["ac", "bc", "ad", "e"];
var result = arr1 .sort(function(i, j){return arr2[i].localeCompare(arr2[j])})
document.write(result );
我的意图是要排序数组1
根据数组2
。我期待的结果是 1,3,2,4
,但事实证明这是 2,1,3,4
任何人都可以找出原因?谢谢
my intention was to sort array1
based on array2
. I was expecting the result to be 1,3,2,4
, but as it turns out it is 2,1,3,4
can anyone figure out why? Thanks
推荐答案
数组是0索引,让你的排序功能启动第二和通过第五一路进行比较;忽略第一元件和事实,即不存在第五元素
Arrays are 0-indexed, so your sort function starts comparing with the second and all the way through the fifth; ignoring the first element and the fact that there is no 5th element.
插入-1排序函数应该修复它:
Inserting a -1 in the sort function should fix it:
arr1.sort(function(i, j){
return arr2[i-1].localeCompare(arr2[j-1])
});
的结果确实 [1,3,2,4]
这篇关于JavaScript中,排序ARRAY1基于arry2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文