英文:
Finding number of occurrences with key-value pair object in javascript
问题
在Udemy的JavaScript课程中,有一个挑战,涉及创建一个包含键-值
对的对象
,并找到每个键的出现次数
。因此,键
是数组元素
,而每个键的值
是该键的出现次数
。
然而,挑战的解决方法如下所示:
const sequential = ["first", "second", "third", "forth", "first", "first"];
const sequentialObject1 = {};
const sequentialObject2 = {};
for (const seq of sequential) {
// 方法一:
sequentialObject1[seq] ? sequentialObject1[seq]++ : (sequentialObject1[seq] = 1);
// 方法二:
sequentialObject2[seq]++ || (sequentialObject2[seq] = 1);
}
console.log(sequentialObject1);
console.log(sequentialObject2);
我无法理解的是,提供的解决方法如何在没有比较过程
的情况下找到出现次数
。在我看来,这个解决方法似乎与查找出现次数没有任何关系,但实际上它确实可以找到它们。
我理解递增运算符
的作用,但不理解比较过程
,或者它是如何发生的!
所以,你能否让我理解背后发生了什么?
谢谢你的帮助。
英文:
On the Udemy Javascript course, there was a challenge, which was about creating an object
with key-value
pair from the array
and finding the number of occurrences
of each key. Thus, the key
is the array element
, and the value
of each key is the number of occurrences
of that key.
However, the solution to the challenge was the following two methods.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const sequential = ["first", "second", "third", "forth", "first", "first"];
const sequentialObject1 = {};
const sequentialObject2 = {};
for (const seq of sequential) {
// Method One:
sequentialObject1[seq] ? sequentialObject1[seq]++ : (sequentialObject1[seq] = 1);
// Method Two:
sequentialObject2[seq]++ || (sequentialObject2[seq] = 1);
}
console.log(sequentialObject1);
console.log(sequentialObject2);
<!-- end snippet -->
The thing that I couldn't understand is, how the provided solution could find the number of occurrences
when there is no comparison process
to compare and find the occurrences. The solution seems to me like has nothing to do with finding the number of occurrences, but in fact, it can find them.
I understand what the increment operator
does, but don't understand the comparison process
, or how it happens!
So, could you please make me understand what is happening behind the scenes?
Thanks for your help.
答案1
得分: 1
这里的技巧是使用对象 sequentialObject
。它是一个字典,用于跟踪 sequential
中的值。当在循环中首次找到值时,它会将其添加到 sequentialObject
中,计数为 1,每次再次找到该值时,该值都会递增,一旦所有项目都完成,它会提供值及其计数的字典。
sequentialObject[seq] ? sequentialObject[seq]++ : (sequentialObject[seq] = 1)
翻译成:如果 seq
存在于 sequentialObject
中,则增加其值,否则将其值设置为 1。
英文:
The trick here is using the object sequentialObject
. It is a dictionary which keeps track of value in sequential
. When the first occurrence of value is found inside the for loop it is added to the sequentialObject with count 1 and every time the value is found again the value is incremented, once all the items are done it gives the dictionary of values and their count.
sequentialObject[seq] ? sequentialObject[seq]++ : (sequentialObject[seq] = 1) translates to: if seq
exists in sequentialObject
then increment its value else set its value to 1.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论