将字符串-数字对添加到数组中(从数组中),这样重复出现的字符串就会递增,而不是再次添加。

问题描述 投票:0回答:2

如何从一个数组(项目-数字对)中插入项目,以便在项目已经被添加的情况下,增加与项目相关的数字?

因此,当我们第一次添加项目时,我们将与它相关的数字设置为1。

我这样做的原因是希望在输入数组中,有一个项目列表,上面有一个它们出现次数的数字。

如果有更好的方法来接收这个结果,我也很乐意接受这些答案。

javascript arrays algorithm object associative-array
2个回答
0
投票

在 Python 中,你可以使用一个字典 (称为 map 在某些其他语言中)。)

li = ['Item#1', 'Item#2', 'Item#3', 'Item#1', 'Item#4', 'Item#1']

dict_map = {}  # we can also use defaultdict

for item in li:
    dict_map[item] = dict_map.get(item, 0) + 1

print(dict_map)

输出。

{'Item#1': 3, 'Item#2': 1, 'Item#3': 1, 'Item#4': 1}

你可以使用相当于这个的JavaScript。


0
投票

let array = ['apple', 'cherry', 'orange'];

let res = {};

array.forEach(x => res[x] = 0);

function add(item) {
  res[item]++;
  document.getElementById(item).innerHTML = res[item]++;

  console.log(res);
}
<div>Apple <span id="apple">0</span></div>
<div>Cherry <span id="cherry">0</span></div>
<div>Orange <span id="orange">0</span></div>

<button onclick="add('apple')">addApple</button>
<button onclick="add('cherry')">addCherry</button>
<button onclick="add('orange')">addOrange</button>
© www.soinside.com 2019 - 2024. All rights reserved.