Arrays and Iteration
Iterating Object Keys
Walk an object's keys and read its values.
Iterating Object Keys
object_keys.js
const bonus = 0;
const keys = Object.keys({ pen: 2, pad: 5, ink: 8 });
let total = 0;
for (const k of keys) {
const price = ({ pen: 2, pad: 5, ink: 8 })[k];
total += price + bonus;
}
console.log("count=" + keys.length);
console.log("total=" + total);
Follow the Keys
Object.keysreturnspen,pad, andink.- The matching prices are
2,5, and8. - The default
bonusis0. - Each loop pass adds
price + bonus. - The script prints
count=3andtotal=15. | key | price | added with bonus 0 | | --- | --- | --- | | pen | 2 | 2 | | pad | 5 | 5 | | ink | 8 | 8 | | total | - | 15 |
object-keys
`Object.keys` returns an array of an object's property names. Looping those keys reads each value, here summing them into a total.
Exercise: object_keys.js
Reproduce count=3 and total=15, then use the pinned bonus variants 10 and 100 to predict totals 45 and 315.