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
]

更新於: 17-Oct-2020

81 次瀏覽

開啟你的 職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.