简体   繁体   中英

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. Since we're already in the execution context of the object: movie, in this example. 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?

Can these "key-type" values also be logged with 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. In that example, movie is the object. The keys of the movie object are title , releaseYear , rating and director . Key is just another name for 'property' by the way.

In the showProperties function, you loop through each key -- ie. at every iteration, key is at first title , then releaseYear , and so on. obj[key] in the first iteration would be movie['title'] , which would give a value of a .

The console logs show the key, followed by the value of movie[key] . Hence the key of title , and the value of a for the first one.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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