字符串中到最近元音的距离 - JavaScript
javascriptweb developmentfront end technologyobject oriented programming更新于 2025/12/6 23:40:17
我们需要编写一个 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 ]
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

