【发布时间】:2016-08-28 15:45:54
【问题描述】:
我编写了用于确定字符串数组中第 n 个最长字符串的代码。下面我列出了 Codewars kata 中的测试用例。
说明:实现函数longest(array,n),你将得到一个字符串数组,然后返回该数组中第n个最长的字符串。例如arr = ['Hello','World','Codewars','Katas'] n = 3;应该返回 'World' 因为 'Codewars' 长度 = 8 , 'Hello' 长度 = 5,所以这是第二长的单词,然后是 'World' (虽然单词长度也是 5,'World' 在 'Hello' 之后大批)。当单词具有相同的长度时,按照它们在数组中的存在顺序来处理它们。数组永远不会为空,并且 n > 0 永远。
Test.assertEquals(longest(['Hello','World','Codewars','Katas'],3),'World');
Test.assertEquals(longest(['Hello','World','Codewars','Katas'],4),'Katas');
Test.assertEquals(longest(['aa', 'bb', 'cc', 'dd', 'eee', 'b', 'f', 'ff', 'hhh', 'gggg'],4),'aa');
Test.assertEquals(longest(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'k'],1),'a');
Test.assertEquals(longest(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'k','l'],1),'a');
我已经通过了所有的 codewars 测试用例,但最后一个例外,数组以“l”结尾。我的排序代码行似乎将“f”放在了这个测试用例的第零位,我不明白为什么。
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”放在第零位。
【问题讨论】:
-
您的排序功能正在测量长度。当所有物品的长度相同时,您为什么会期望任何特定的顺序?
-
非常感谢您的帮助。我非常感谢您对我的问题的贡献...
标签: javascript arrays string sorting string-length