JavaScript 中的元音间隙数组

javascriptweb developmentfront end technologyobject oriented programming更新于 2026/1/30 22:04: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
]

相关文章


有用资源