遍历对象
此页面需较新浏览器(支持 SharedArrayBuffer)。请升级 Chrome、Edge、Firefox 或 Safari 至最新版本。
English
Visit every key of an object
- An object has no index
0, 1, 2, so a plainforloop cannot walk through it. for (const key in obj)gives you each key in turn.- Read the value with square brackets:
obj[key]. The dot form,obj.key, would look for a key literally called "key".
![for (const fruit in stock) visits apples, pears and plums in turn; stock[fruit] reads 4, 0 and 7](/static/code/javascript/for-in.png)
English
const stock = { apples: 4, pears: 0, plums: 7 };
for (const fruit in stock) {
console.log(fruit, stock[fruit]);
}
// → apples 4
// → pears 0
// → plums 7
English
Keys, values and entries as arrays
Object.keys(obj)gives an array of the keys.Object.values(obj)gives an array of the values.Object.entries(obj)gives an array of[key, value]pairs. You can loop over it withfor…of.
English
const stock = { apples: 4, pears: 0, plums: 7 };
console.log(Object.keys(stock)); // → ["apples","pears","plums"]
console.log(Object.values(stock).length); // → 3
for (const [fruit, count] of Object.entries(stock)) {
if (count === 0) {
console.log(fruit + " sold out");
}
}
// → pears sold out
English
Worked example: total and best
Question: an object holds each student's score. Find the total, and the name with the highest score.
const scores = { Ada: 82, Ben: 95, Cy: 77 };
let total = 0;
let best = "";
for (const name in scores) {
total += scores[name];
if (best === "" || scores[name] > scores[best]) {
best = name;
}
}
console.log(total); // → 254
console.log(best); // → Ben
The loop keeps the name of the best student, not just the score, because the score alone would not tell you who it belongs to.
English
Watch out
for…inis for objects. On an array, usefor…of, which gives the values.Object.keys(obj).lengthcounts the keys. An object has no.lengthof its own.
English
Common mistakes
- Writing
stock.fruitinside the loop. It looks for a key namedfruitand givesundefined. Usestock[fruit]. - Using
for…ofdirectly on an object. It throws "stock is not iterable". Loop overObject.entries(stock)instead. - Starting
bestat0when it should hold a name. Start from""or from the first key.
English
Now you try
- Loop over an object's keys, then add up its values.
- Press Check answer to test it.
难度 1/5 · 今日首次完成可获 100 金币及少量额外奖励
const pet = { name: "Rex", age: 3 }。用 for…in 打印每个键和它的值,中间用空格隔开(name Rex,然后 age 3)。
点击“运行”查看此处输出。
难度 2/5 · 今日首次完成可获 140 金币及少量额外奖励
编写 totalItems(cart),把对象(例如 { pens: 3, books: 2 },结果是 5)里的所有值加起来。空对象得 0。
点击“运行”查看此处输出。
难度 3/5 · 今日首次完成可获 200 金币及少量额外奖励
编写 soldOut(stock),按对象中的顺序返回值为 0 的键组成的数组。soldOut({ apples: 4, pears: 0, figs: 0 }) 得到 ["pears", "figs"]。
点击“运行”查看此处输出。