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 ]
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
安卓
Python
C 語言
C++
C#
MongoDB
MySQL
Javascript
PHP