[英]Javascript - 128_findShortestWordAmongElements — Given an array of different type elements, find the string with the shortest word
我正在从Hackreactor进行练习,而我目前仍停留在该练习上:
/*
* Notes:
* If there are ties, it should return the first element to appear in the given array.
* Expect the given array to have values other than strings.
* If the given array is empty, it should return an empty string.
* If the given array contains no strings, it should return an empty string.
var output = findShortestWordAmongMixedElements([4, 'two', 2, 'three']);
console.log(output); // --> 'two'
*/
到目前为止,这就是我所拥有的:
function findShortestWordAmongMixedElements(arr) {
// your code here
var array = [];
for (var i = 0; i < arr.length; i++) {
if (typeof arr[i] === 'string') {
array.push(arr[i]);
array.sort(function(a,b) {
return a.length - b.length;
});
return array[0];
}
}
}
它返回我想要的单词,但我无法满足失败条件。 我尝试过的是,我在return array [0]之后放置了一条if语句,如果返回的元素类型未定义,它将返回一个空字符串。 这根本不起作用。 我还为if(arr.length> 0)放置了一条if语句,如果使用||将该数组为空,则返回一个空字符串。 这有效,但另一个无效。 有没有办法可以在代码中实现这些失败条件?
var min = Math.min.apply(Math, arr.map(function(str) { return str.length; }));
其中“ arr”将是您的数组
该程序不起作用,因为它返回找到的第一个字符串:
for (var i = 0; i < arr.length; i++) { if (typeof arr[i] === 'string') { // ... return array[0];
循环内不能有return
语句,因为在迭代所有项目之前,您不知道哪个项目最短。
与其构建临时的字符串数组,进行排序并返回最短元素,不如在迭代时跟踪最短元素。 不仅节省内存,而且排序步骤使您的实现效率降低O(n log n)
,而不是O(n)
。
function findShortestWordAmongMixedElements(arr) {
var shortest, i, item;
var minLength = Number.MAX_SAFE_INTEGER;
for (i = 0; i < arr.length; i++) {
item = arr[i];
if (typeof item === 'string') {
if (item.length < minLength) {
shortest = item;
minLength = shortest.length;
}
}
}
return shortest || "";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.