模块 5 · 第 2 课(共 4)课程中的18/32~10 min
模块课程(2/4)
为…的和为…在
JavaScript has two "ergonomic" loops that should not be confused:
for…ofiterates the values of an iterable collection (array, string, Set, Map...).for…initerates the enumerable keys of an object.
They are close cousins and easily swapped — using the wrong one is one of the language's first traps.
for…of for arrays and strings
JS
const colori = ['rosso', 'verde', 'blu'];
for (const c of colori) {
console.log(c); // 'rosso', 'verde', 'blu'
}
for (const ch of 'abc') {
console.log(ch); // 'a', 'b', 'c'
}It does not give you the index. If you also need the index, use entries():
JS
for (const [i, c] of colori.entries()) {
console.log(i, c); // 0 rosso, 1 verde, 2 blu
}for…in for objects
JS
const utente = { nome: 'Anna', eta: 30, citta: 'Roma' };
for (const chiave in utente) {
console.log(chiave, utente[chiave]); // 'nome' 'Anna', ...
}When NOT to confuse them
JS
const colori = ['rosso', 'verde', 'blu'];
// SBAGLIATO: stampa gli indici come stringhe!
for (const x in colori) {
console.log(x); // '0', '1', '2'
}
// GIUSTO
for (const x of colori) {
console.log(x); // 'rosso', 'verde', 'blu'
}Try it
锻炼#js.m5.l2.e1
尝试:0加载中...
Define `concat(words)` that, given a list of strings, returns a string with all of them concatenated, separated by a space. Use for…of.
正在加载编辑器...
显示提示
Accumulate into a string; add the space only if it is not the first word.
3 次尝试后可用的解决方案
Review exercise
锻炼#js.m5.l2.e2
尝试:0加载中...
Define `positiveValues(obj)` that returns an array with the object's values that are numbers > 0. Use for…in. The order must match the iteration order of the keys.
正在加载编辑器...
显示提示
Loop with for...in over the keys, filter with typeof and > 0, push into the results.
3 次尝试后可用的解决方案