模块 5 · 第 2 课(共 4)课程中的18/32~10 min
模块课程(2/4)
为…的和为…在
JavaScript 有两个“符合人体工程学”的循环,不应混淆:
for…of迭代可迭代集合(数组、字符串、Set、Map...)的值。for…in迭代对象的可枚举键。
它们是近亲并且很容易互换——使用错误的一个是该语言的第一个问题 陷阱。
for…of 用于数组和字符串
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'
}它不会给你索引。如果您还需要索引,请使用 entries():
JS
for (const [i, c] of colori.entries()) {
console.log(i, c); // 0 rosso, 1 verde, 2 blu
}for…in 对于对象
JS
const utente = { nome: 'Anna', eta: 30, citta: 'Roma' };
for (const chiave in utente) {
console.log(chiave, utente[chiave]); // 'nome' 'Anna', ...
}什么时候不要让他们感到困惑
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'
}尝试一下
锻炼#js.m5.l2.e1
尝试:0加载中...
定义“concat(words)”,给定一个字符串列表,返回一个字符串,其中所有字符串都连接在一起,并用空格分隔。用于…的。
正在加载编辑器...
显示提示
累加成字符串;仅当不是第一个单词时才添加空格。
3 次尝试后可用的解决方案
复习练习
锻炼#js.m5.l2.e2
尝试:0加载中...
定义 `positiveValues(obj)` 返回一个数组,其中对象的值是数字 > 0。使用 for...in。该顺序必须与键的迭代顺序匹配。
正在加载编辑器...
显示提示
在键上使用 for...in 循环,使用 typeof 和 > 0 进行过滤,推入结果。
3 次尝试后可用的解决方案