给定一个字符串,我们需要编写一个函数来创建一个对象,该对象将每个字母的索引存储在数组中。字符串的字母(元素)必须是对象的键
索引应存储在数组中,并且这些数组是值。
例如-
如果输入字符串是-
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 ] }