簡體   English   中英

如何判斷混合數組是否包含字符串元素?

[英]How to tell if a mixed array contains string elements?

我正在研究的練習問題:

編寫一個名為“ findShortestWordAmongMixedElements”的函數。

給定一個arrayfindShortestWordAmongMixedElements返回給定數組中最短的字符串。

筆記:
*如果有聯系,它應該返回出現在給定數組中的第一個元素。
*期望給定數組具有字符串以外的值。
*如果給定數組為空,則應返回一個空字符串。
*如果給定的數組不包含任何字符串,則應返回一個空字符串。

這是我目前編寫的代碼:

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??) ,但不確定如何處理。

有什么提示嗎? 甚至更聰明的方式來編寫此功能

“一切正常,但我不知道如何通過“如果給定數組不包含字符串”測試。

您已經在使用.filter()來獲取僅包含字符串的數組。 如果result數組為空,則沒有字符串。 (我假設您不需要我為此顯示代碼,因為您已經具有測試數組是否為空的代碼。)

您可以使用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的 過濾器更有效,因為它只遍歷數組一次。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM