我找到了这个数组中重复元素的计数代码
null
const a = ['first', 'first', 'second'];
const obj = {};
for (let i = 0; i < a.length; i++) {
const current = a[i];
if (obj[current]) {
obj[current] += 1
}else {
obj[current] = 1
}
}
console.log(obj)
null
我很难弄清楚if语句是如何创建对象的。 我认为主要的逻辑是:
if (obj[current]) {
obj[current] += 1
}else {
obj[current] = 1
}
if语句chack if在obj
中存在一个键,它增加了数字obj[current]+=1
,但是这个代码如何将数组中的值设置为键,因为obj[current]
输出的是数字,而不是键。 代码如何设置对象的键?
如果数组a
中的当前元素还不存在于obj
中,则其默认值为1。 这个粗略的调用堆栈图可能会有帮助
i | a[i] | obj
0 | 'first' | { first: 1 }
1 | 'first' | { first: 2 }
2 | 'second' | { first: 2, second: 1 }
我猜你在这句话上误会了
输出数字,而不是钥匙。 代码如何设置对象的键?
因此,如果我在for中添加一个控制台,那么您可以在基于I
的每次迭代中轻松地看到obj[current]
的值,当obj不包含键(基于您的if条件)时,它返回未定义,当它在对象中存在一个数字(即键)时,您将其递增1。
null
const a = ['first', 'first', 'second'];
const obj = {};
for (let i = 0; i < a.length; i++) {
const current = a[i];
console.log("When current="+current+" then obj[current]="+obj[current]);
if (obj[current]) {
obj[current] += 1
}else {
obj[current] = 1
}
}
console.log(obj)
var obj = {}
if (obj[current]) {
obj[current] += 1;
} else {
obj[current] = 1;
}
obj
是一种字典结构,也称为关联数组。
字典键可以是一般编程中的任何内容。 在javascript中,它通常是字符串或数字类型。 您可以使用obj['key']
在字典中获取或设置值。 您还可以使用变量来表示字典键,例如:obj[current]
。
null
const obj = {}
const keyName = 'stack'
obj[keyName] = 'overflow';
console.log(obj); // { "stack": "overflow" }
obj['stack'] = 'exchange';
console.log(obj); // { "stack": "exchange" }