Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 第n长串分拣_Javascript_Arrays_String_Sorting_String Length - Fatal编程技术网

Javascript 第n长串分拣

Javascript 第n长串分拣,javascript,arrays,string,sorting,string-length,Javascript,Arrays,String,Sorting,String Length,我已经编写了确定字符串数组中第n个最长字符串的代码。下面我列出了Codewars kata中的测试用例 说明:实现函数longest(array,n),其中将为您提供一个字符串数组,然后返回该数组中第n个最长的字符串。e、 g.arr=['Hello'、'World'、'Codewars'、'Katas']n=3;应该返回'World',因为'Codewars'长度=8,'Hello'长度=5,所以这是第二长的单词,然后是'World'(虽然单词长度也是5,'World'在数组中位于'Hello

我已经编写了确定字符串数组中第n个最长字符串的代码。下面我列出了Codewars kata中的测试用例

说明:实现函数longest(array,n),其中将为您提供一个字符串数组,然后返回该数组中第n个最长的字符串。e、 g.arr=['Hello'、'World'、'Codewars'、'Katas']n=3;应该返回'World',因为'Codewars'长度=8,'Hello'长度=5,所以这是第二长的单词,然后是'World'(虽然单词长度也是5,'World'在数组中位于'Hello'之后)。当单词长度相同时,请按它们在数组中的存在顺序处理它们。数组将永远不会为空,并且n始终大于0

我已经通过了所有的codewars测试用例,但最后一个例外,数组以“l”结尾。我的分类代码行似乎将这个测试用例的“f”放在了第0位,我不明白为什么

function longest(arr, n) {
  arrLength = [];
  arr.sort(function(a, b){return b.length - a.length});
  console.log(arr);
  arr.forEach(function(numArray){
    return arrLength.push(numArray.length);
  });
  return arr[n-1];
}

console.log(longest(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'k'],1));
// Sorted Array: ["a", "b", "c", "d", "e", "f", "g", "h", "i", "k"]
// returns a
console.log(longest(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'k', 'l'],1));
// Sorted Array: ["f", "a", "c", "d", "e", "b", "g", "h", "i", "k", "l"]
// returns f

我似乎不明白为什么我的排序函数在将“l”添加到字符串数组的末尾时将“f”放在第0位。

如果使用内置的排序函数,可能该函数会根据数组的不同而改变排序算法,因为相同长度的字符串没有相同的行为。甚至可能这也取决于浏览器

我建议您通过使用具有确定排序功能(快速排序,无论什么…)的库来改变这一点。并检查是否再次发生这种情况。

在MSIE上工作正常

在Microsoft Internet Explorer(任何版本)上进行的快速测试将为您提供的功能提供以下结果:

>> longest(['a','b','c','d','e','f','g','h','i','k'],1); 
 a,b,c,d,e,f,g,h,i,k 
"a" 
>> console.log(longest(['a','b','c','d','e','f','g','h','i','k','l'],1)); 
 a,b,c,d,e,f,g,h,i,k,l 
 a 
>> console.log(longest(['a','b','c','d','e','f','g','h','i','k','l',"m","n"],1)); 
 a,b,c,d,e,f,g,h,i,k,l,m,n 
 a 

p、 美国:所有非MS浏览器在sort()的稳定性方面都存在问题。

您的排序函数正在测量长度。当所有商品的长度相同时,您为什么希望得到任何特殊订单?非常感谢您的帮助。我非常感谢您对我的问题所作的贡献……这应该是一个评论而不是答案。@bhspencer这是一个答案:使用本机排序功能以外的其他功能。是的,我使用的是chrome。正如您所说,不同浏览器的sort()看起来有所不同。
>> longest(['a','b','c','d','e','f','g','h','i','k'],1); 
 a,b,c,d,e,f,g,h,i,k 
"a" 
>> console.log(longest(['a','b','c','d','e','f','g','h','i','k','l'],1)); 
 a,b,c,d,e,f,g,h,i,k,l 
 a 
>> console.log(longest(['a','b','c','d','e','f','g','h','i','k','l',"m","n"],1)); 
 a,b,c,d,e,f,g,h,i,k,l,m,n 
 a