TS学习之for..of

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"
}
复制代码

posted on 2018-07-19 10:50  防空洞123  阅读(440)  评论(0编辑  收藏  举报

导航