[翻译]Javascript中的for of与for in

Javascript中的for of与for in

for...offor...in 为开发者提供了一种简单便捷的循环执行语法,其可以遍历任何可迭代对象和可枚举的对象,例如字符串等等

下面是一些可以帮助大家理解和记忆的使用案例

0x00 for of

使用for...of可以遍历例如数组这样可以迭代的变量:

let animals = ['鸡', '猪', '羊', '兔'];
let names = ['Gertrude', 'Henry', 'Melvin', 'Billy Bob'];

for (let animal of animals) {
  // Random name for our animal
  let nameIdx = Math.floor(Math.random() * names.length);

  console.log(`${names[nameIdx]} the ${animal}`);
}

// Henry the 鸡
// Melvin the 猪
// Henry the 羊
// Billy Bob the 兔

字符串也是一种可迭代的类型,因此开发者也可以用for...of去遍历字符串

let str = 'abcde';

for (let char of str) {
  console.log(char.toUpperCase().repeat(3));
}

// AAA
// BBB
// ...

for...of也可用于遍历函数的arguments对象mapset生成器(generators)DOM节点集合


0x01 for…in

使用for...in可以遍历对象的所有属性(object的keys):

let oldCar = {
  make: 'Toyota',
  model: 'Tercel',
  year: '1996'
};

for (let key in oldCar) {
  console.log(`${key} --> ${oldCar[key]}`);
}

// make --> Toyota
// model --> Tercel

也可以借助for...in去遍历例如数组或字符串这样可迭代的索引值:

let str = 'Turn the page';

for (let index in str) {
  console.log(`Index of ${str[index]}: ${index}`);
}

// Index of T: 0
// Index of u: 1

原文链接:https://alligator.io/js/for-of-for-in-loops/

发表评论 / Comment

用心评论~

金玉良言 / Appraise
DYBOY站长已认证
2021-05-27 18:13
for in会遍历对象原型链上的属性,可以使用Object.keys(obj)拿到keys的数组(可迭代对象)
便宜vpsLV 1
2020-08-26 09:59
交换链接吗

Warning: Cannot modify header information - headers already sent by (output started at /www/wwwroot/blog.dyboy.cn/content/templates/dyblog/footer.php:56) in /www/wwwroot/blog.dyboy.cn/include/lib/view.php on line 23