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