使用 JavaScript 计算在字符串数组的字母表中占据位置的字母数

问题

我们需要编写一个 JavaScript 函数,该函数接受英文小写字母字符串数组。

我们的函数应该将输入数组映射到一个数组,该数组的对应元素是在索引中具有相同从 1 开始的索引与其在字母表中从 1 开始的索引的字符数的计数。

例如 -

字符串 'akcle' 的计数将为 3,因为字符 'a'、'c' 和 'e' 在字符串和英文字母中分别具有 1、3 和 5 的基于 1 的索引。

示例

以下是代码 -

const arr = ["abode","ABc","xyzD"];

const findIndexPairCount = (arr = []) => {

   const alphabet = 'abcdefghijklmnopqrstuvwxyz'

   const res = [];

   for (let i = 0; i < arr.length; i++) {

      let count = 0;

      for (let j = 0; j < arr[i].length; j++) {

         if (arr[i][j].toLowerCase() === alphabet[j]) {

            count++;

         }

      }

      res.push(count);

   }

   return res;

};

console.log(findIndexPairCount(arr));

输出结果
[ 4, 3, 1 ]

以上是 使用 JavaScript 计算在字符串数组的字母表中占据位置的字母数 的全部内容, 来源链接: utcz.com/z/331787.html

回到顶部