在 JavaScript 中查找字符串中最短的单词

javascriptweb developmentfront end technologyobject oriented programming更新于 2026/1/19 6:36:17

我们需要编写一个 JavaScript 函数,该函数接受一个字符串并返回该字符串中最短的单词。

例如:如果输入字符串是 −

const str = 'This is a sample string';

那么输出应该是 −

const output = 'a';

示例

其代码为 −

const str = 'This is a sample string';
const findSmallest = str => {
   const strArr = str.split(' ');
   const creds = strArr.reduce((acc, val) => {
      let { length, word } = acc;
      if(val.length < length){
         length = val.length;
         word = val;
      };
      return { length, word };
   }, {
      length: Infinity,
      word: ''
   });
   return creds.word;
};
console.log(findSmallest(str));

输出

控制台中的输出 −

a

相关文章


有用资源