字串中最接近母音的距離 - JavaScript


我們需要編寫一個 JavaScript 函式,它接受一個至少含有一個母音的字串,並且我們必須為字串中的每個字元繪製一個數字,表示其離母音的最近距離。

例如:如果字串為

const str = 'vatghvf';

則輸出應為

const output = [1, 0, 1, 2, 3, 4, 5];

示例

以下為程式碼

const str = 'vatghvf';
const nearest = (arr = [], el) => arr.reduce((acc, val) => Math.min(acc,
Math.abs(val - el)), Infinity);
const vowelNearestDistance = (str = '') => {
   const s = str.toLowerCase();
   const vowelIndex = [];
   for(let i = 0; i < s.length; i++){
      if(s[i] === 'a' || s[i] === 'e' || s[i] === 'i' || s[i] === 'o' ||
      s[i] === 'u'){
         vowelIndex.push(i);
      };
   };
   return s.split('').map((el, ind) => nearest(vowelIndex, ind));
};
console.log(vowelNearestDistance(str));

輸出

以下是控制檯中的輸出

[
   1, 0, 1, 2,
   3, 4, 5
]

更新於: 2020 年 9 月 16 日

416 次瀏覽

啟動你的 職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.