如何判断一个混合数组是否包含字符串元素?

3

我正在处理的练习问题:

编写一个名为“findShortestWordAmongMixedElements”的函数。

给定一个数组,findShortestWordAmongMixedElements返回给定数组中最短的字符串。

注:
* 如果存在并列,它应该返回在给定数组中出现的第一个元素。
* 期望给定数组存在字符串以外的值。
* 如果给定数组为空,则应返回空字符串。
* 如果给定数组不包含字符串,则应返回一个空字符串。

这是我当前编写的代码:

function findShortestWordAmongMixedElements(array) {
  if (array.length === 0)) {
    return '';
  }
  var result = array.filter(function (value) {
    return typeof value === 'string';
  });
  var shortest = result.reduce(function (a, b) {
    return a.length <= b.length ? a : b;
  });
  return shortest;
}

var newArr = [ 4, 'two','one', 2, 'three'];

findShortestWordAmongMixedElements(newArr);
//returns 'two'

一切都正常,但我无法弄清如何通过“如果给定的数组不包含字符串”的测试。 我在考虑在if语句中添加某种!array.includes(string??),但不确定该怎么做。

有任何提示吗?或者更聪明的编写此函数的方法

2个回答

4

"所有东西都好使,但我不知道如何通过“如果给定的数组不包含字符串”测试。"

您已经使用了.filter()来获取仅包含字符串的数组。 如果result数组为空,则没有字符串。 (我假设您不需要我展示代码,因为您已经有可以测试数组是否为空的代码。)


1
你可以使用reduce和初始值,如null(或任何特定的非字符串值)来实现这一点。查找最短的字符串,如果没有字符串,reduce将返回初始值。因此,如果返回了初始值,则返回一个空字符串。

function getShortest(arr) {
  return arr.reduce(function(acc, value) {
    if (typeof value == 'string') {
      if (acc === null || value.length < acc.length) {
        acc = value;
      }
    }
    return acc;
  }, null) || '';
}

var test0 = [ 4, 'two','one', 2, 'three']; // Has strings
var test1 = [ 4, {},[], 2, new Date()];    // No strings
var test2 = [];                            // Empty
var test3 = [ 4, 'two','', 2, 'three']; // Has strings, shortest empty

console.log('test0: "' + getShortest(test0) + '"'); // "two"
console.log('test1: "' + getShortest(test1) + '"'); // no strings
console.log('test2: "' + getShortest(test2) + '"'); // empty
console.log('test3: "' + getShortest(test3) + '"'); // ""

这种方法比使用reducefilter更高效,因为它只需要遍历一次数组。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接