假设我们有一个长字符串,代表一个像这样的数字-
const str = '11222233344444445666';
我们需要编写一个包含一个这样的字符串的JavaScript函数。我们的函数应该返回一个对象,该对象应该为字符串中的每个唯一数字分配一个唯一的“ id”属性,并为另一个属性“ count”分配一个存储该数字出现在字符串中的次数的计数。
因此,对于上述字符串,输出应类似于-
const output = {
'1': { id: '1', displayed: 2 },
'2': { id: '2', displayed: 4 },
'3': { id: '3', displayed: 3 },
'4': { id: '4', displayed: 7 },
'5': { id: '5', displayed: 1 },
'6': { id: '6', displayed: 3 }
};为此的代码将是-
const str = '11222233344444445666';
const countNumberFrequency = str => {
const map = {};
for(let i = 0; i < str.length; i++){
const el = str[i];
if(map.hasOwnProperty(el)){
map[el]['displayed']++;
}else{
map[el] = {
id: el,
displayed: 1
};
};
};
return map;
};
console.log(countNumberFrequency(str));输出结果
控制台中的输出将是-
{
'1': { id: '1', displayed: 2 },
'2': { id: '2', displayed: 4 },
'3': { id: '3', displayed: 3 },
'4': { id: '4', displayed: 7 },
'5': { id: '5', displayed: 1 },
'6': { id: '6', displayed: 3 }
}