for..of
会遍历可迭代的对象,调用对象上的Symbol.iterator
方法(可迭代对象,数组,字符串等)
let arr = ["hello", "ts", "test"];for (let item of arr) { console.log(item)}//"hello", "ts", "test"
for...of VS for...in(均可迭代一个列表。但是用于迭代的值却不同,for..in
迭代的是对象的 键 的列表,而for..of
则迭代对象的键对应的值。)
let list = [4, 5, 6];for (let i in list) { console.log(i); // "0", "1", "2",}for (let i of list) { console.log(i); // "4", "5", "6"}
let pets = {1:"Cat",2:"Dog",3:"Hamster"}for (let pet in pets) { console.log(pet); // 1,2,3}for (let pet of pets) { console.log(pet); // "Cat", "Dog", "Hamster"}