使用JavaScript按顺序存储整数计数
假设我们有一个长字符串,代表一个像这样的数字-
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 }
}热门推荐
10 读书祝福语女生短句简短
11 感谢同事新婚祝福语简短
12 感谢教官文案祝福语简短
13 员工聚会蛋糕祝福语简短
14 元宵发客户祝福语简短
15 给团队信心祝福语简短
16 医美的祝福语大全简短
17 异国姻缘的祝福语简短
18 兄妹拍照祝福语简短的话