将字符串的字母映射到数组对象 - JavaScript

javascriptweb developmentfront end technologyobject oriented programming更新于 2025/12/12 9:48:17

给定一个字符串,我们需要编写一个函数来创建一个对象,该对象将每个字母的索引存储在数组中。字符串的字母(元素)必须是对象的键

索引应存储在数组中,这些数组是值。

例如 −

如果输入字符串是 −

const str = 'cannot';

那么输出应该是 −

const output = {
   'c': [0],
   'a': [1],
   'n': [2, 3],
   'o': [4],
   't': [5]
};

示例

以下是代码 −

const str = 'cannot';
const mapString = str => {
   const map = {};
   for(let i = 0; i < str.length; i++){
      if(map.hasOwnProperty(str[i])){
         map[str[i]] = map[str[i]].concat(i);
      }else{
         map[str[i]] = [i];
      };
   };
   return map;
};
console.log(mapString(str));

输出

以下是控制台中的输出 −

{ c: [ 0 ], a: [ 1 ], n: [ 2, 3 ], o: [ 4 ], t: [ 5 ] }

相关文章


有用资源