简体   繁体   English

键/值对的值也可以是键吗?

[英]can a value of a key/value pair also be a key?

enter image description here在此处输入图像描述

In this example, to log the value of the properties with the keys "title" and "director", obj[key] is used.在此示例中,要使用键“title”和“director”记录属性的值,使用 obj[key]。 Since we're already in the execution context of the object: movie, in this example.因为我们已经在 object: 电影的执行上下文中,在这个例子中。 Obj in "Obj[key]" must refer to title: 'a', and director: 'b' and key to the value of these objects, so "a" and "b" are noted as keys, right? "Obj[key]" 中的 Obj 必须引用 title: 'a',director: 'b' 和 key 指向这些对象的值,所以 "a" 和 "b" 被标注为键,对吧?

Can these "key-type" values also be logged with obj[value]?这些“键类型”值也可以用 obj[value] 记录吗?


This is an example in a course, but the instructor is not explaining it well, so I've probably spent two hours at this point trying to understand the nomenclature.这是课程中的一个例子,但讲师解释得不好,所以我可能已经花了两个小时试图理解命名法。 I hope this is correct, and if not;我希望这是正确的,如果不是; I'd really appreciate whatever misstep I'm making.我真的很感激我所犯的任何错误。

Thanks in advance提前致谢

Putting the code from the image here for easier reference, have also changed the logs slightly to make it clear which is the key and which is the value:将图像中的代码放在这里以便于参考,还稍微更改了日志以明确哪个是关键,哪个是值:

 const movie = { title: 'a', releaseYar: 2018, rating: 4.5, director: 'b' }; showProperties(movie); function showProperties(obj) { for (let key in obj) if (typeof obj[key] === 'string') { console.log('key -->', key); console.log('value -->', obj[key]); } }

Nope, 'a' and 'b' in that example are not keys, they are values.不,该示例中的“a”和“b”不是键,它们是值。 In that example, movie is the object.在该示例中, movie是 object。 The keys of the movie object are title , releaseYear , rating and director .电影releaseYear的关键是title 、发行年份、 ratingdirector Key is just another name for 'property' by the way.顺便说一下,密钥只是“财产”的另一个名称。

In the showProperties function, you loop through each key -- ie.showProperties function 中,您循环遍历每个键 - 即。 at every iteration, key is at first title , then releaseYear , and so on.在每次迭代中, key首先是title ,然后是releaseYear ,依此类推。 obj[key] in the first iteration would be movie['title'] , which would give a value of a .第一次迭代中的obj[key]将是movie['title'] ,它会给出a的值。

The console logs show the key, followed by the value of movie[key] .控制台日志显示密钥,然后是movie[key]的值。 Hence the key of title , and the value of a for the first one.因此是title的键,以及第一个的a的值。

Please look at the comment to understand the code and run code.请看评论了解代码并运行代码。

 const movie = { title: "SOmething", releaseDate: 2020, rating: 4.5, director: "Someone", }; function showProperties(object) { for (const key in object) { const value = object[key]; // get value of the key console.log(key, value); // log everything // check if value is type string if (typeof value === "string") { console.log(key, value); // then only if value is string } } } showProperties(movie);

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

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