使用 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 }
}
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP