数组链接,按 typeof 原语和 return 最短长度元素过滤数组

Array chaining, filter array by typeof primitive and return shortest length element

我试图从充满不同类型基元的数组中提取最短字符串的尝试失败了。我究竟做错了什么?还有其他的wa

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) {
    var xs = '';
    var i = 0;
    collection.forEach(function (x) {
               if (typeof x === 'string' && x != '') {
                   xs = (i == 0) ? x : (x.length < xs.length) ? x : xs;
                   i++;
               }
           });
    return xs;
}

你可以这样做 sort.Here 最短的字符串 'to'

var bands = ([30, 'Seconds', 'to', 'Mars', 1, 'Direction', true]);
var strArray = bands.filter(function(item) {
  if (typeof item == "string")
    return item
});
var maxLength, shortStr;
strArray.forEach(function(str) {
  var currLength = str.length;
  if (maxLength == undefined || currLength < maxLength) {
    maxLength = currLength;
    shortStr = str;
  }


});

console.log(shortStr);

希望对您有所帮助

您可以按长度和类型排序,return第一个

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) );