【问题标题】:How to tell if a mixed array contains string elements?如何判断混合数组是否包含字符串元素?
【发布时间】:2017-03-19 05:50:15
【问题描述】:

我正在处理的练习题:

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

给定array,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??),但不知道如何去做。

有什么提示吗?甚至更聪明的方法来编写这个函数

【问题讨论】:

    标签: javascript arrays string


    【解决方案1】:

    “一切正常,但我不知道如何通过“如果给定的数组不包含字符串”测试。”

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

    【讨论】:

      【解决方案2】:

      您可以使用 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) + '"'); // ""

      这应该比使用 reduce 的 filter 更有效,因为它只遍历数组一次。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-08-26
        • 2012-11-25
        • 2017-10-15
        • 1970-01-01
        • 1970-01-01
        • 2012-08-29
        • 2019-10-22
        • 2014-06-18
        相关资源
        最近更新 更多