繁体   English   中英

将数组值设置为 object 键

[英]Set array value as a object key

我发现这段代码计算了数组中的重复元素

 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)

我很难弄清楚这个 if 语句是如何创建 object 的。 我想主要的逻辑在这里:

 if (obj[current]) {
        obj[current] += 1
    }else {
        obj[current] = 1
 }

if 语句检查obj中是否存在一个键,它会增加数字obj[current] += 1 ,但是这段代码如何将数组中的值设置为键,因为obj[current] output 是数字,而不是键。 代码如何设置 object 的密钥?

如果数组a中的当前元素在obj中尚不存在,则其默认值为 1。此粗略的调用堆栈图可能会有所帮助

i |   a[i]   |    obj
0 | 'first'  | { first: 1 }
1 | 'first'  | { first: 2 }
2 | 'second' | { first: 2, second: 1 }
var obj = {}

if (obj[current]) {
  obj[current] += 1;
} else {
  obj[current] = 1;
}

obj是一个字典结构,也称为关联数组

字典键可以是一般编程中的任何类型。 但在 javascript 中,通常字符串或数字类型用作字典键。 您可以使用obj['key']在字典中获取或设置值。 您还可以使用变量来表示字典键,例如: obj[current]

 const obj = {} const keyName = 'stack' obj[keyName] = 'overflow'; console.log(obj); // { "stack": "overflow" } obj['stack'] = 'exchange'; console.log(obj); // { "stack": "exchange" }

您提到的代码检查obj[current]值是否不是null0""undefinedfalse中的任何一个。 如果字典中的键不可用,Dictionary[key] 返回 undefined。

你也可以这样写这部分:

if (obj[current] !== undefined)

所以if (obj[current])检查 obj 字典是否有一个等于 current 的键。 如果密钥可用,它只会增加字典项的值。 如果键不可用,它会将新项目放入具有current键和1值的obj字典。

我猜你对这条线有误解

obj[current] output数字,不是关键 代码如何设置 object 的密钥?

因此,如果我在 for 中添加一个控制台,那么您可以轻松地在基于i的每次迭代中看到obj[current]的值,当 obj 不包含键(基于您的 if 条件)以及它何时返回undefined存在一个数字,即当obj[current]不等于undefined0false""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]) { // when obj[current] not equal undefined, 0, false, "" or null obj[current] += 1 }else { obj[current] = 1 } } console.log(obj)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM