我尝试从充满不同类型基元的数组中提取最短的字符串,但失败了。我究竟做错了什么?还有其他的吗
var bands = ([30, 'Seconds', 'to', 'Mars', 1, 'Direction', true]);
function tinyString(collection) {
var tinyStr = '';
return collection.
filter(function (x) {
return typeof x === 'string'
}).
forEach(function (y) {
if (tinyStr > y){
return tinyStr = y
}
})
}
console.log(bands); // --> 'to'
最佳答案
您可以按长度和类型排序,并返回第一个
var bands = ([30, 'Seconds', 'to', 'Mars', 1, 'Direction', true]);
function tinyString(collection) {
return collection.sort((a,b)=>typeof a === 'string' ? a.length-b.length:1).shift();
}
console.log( tinyString(bands) );
关于javascript - 数组链接,按原语类型过滤数组并返回最短长度元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40711234/