Es6 之for of
能工摹形,巧匠窃意。 -- 毕加索
2016-10-10
<!DOCTYPE HTML> <html> <head> <script src="traceur.js"></script> <script src="es6-bootstrap.js"></script> <script type="text/traceur"> // 请在这里亲自体验下,左侧讲解的知识点。 function *person() { yield "张三"; yield "李四"; yield "王五"; yield "赵六"; yield "田七"; return "老八"; }; for(let i of person()){ document.write(i+","); //张三,李四,王五,赵六,田七, } </script> </head> <body> </body> </html>
//上面代码使用for...of循环,依次显示5个yield语句的值。
//这里需要注意,一旦next方法的返回对象的done属性为true,for...of循环就会中止,
//且不包含该返回对象,所以上面代码的return语句返回的老八,不包括在for...of循环之中。
let nicknames = ['di', 'boo', 'punkeye'];
nicknames.size = 3;
for (let nickname of nicknames) {
console.log(nickname);
}
Result: di, boo, punkeye
for...in 用来遍历对象中的属性:
let nicknames = ['di', 'boo', 'punkeye'];
nicknames.size = 3;
for (let nickname in nicknames) {
console.log(nickname);
}
Result: 0, 1, 2, size
对比方可以看到这一微弱的变化 所引发的美感!
let nicknames = ['di', 'boo', 'punkeye'];
nicknames.size = 3;
for (let nickname of nicknames) {
console.log(nickname);
}
Result: di, boo, punkeye
for...in 用来遍历对象中的属性:
let nicknames = ['di', 'boo', 'punkeye'];
nicknames.size = 3;
for (let nickname in nicknames) {
console.log(nicknames[nickname]);
}
Result:di, boo, punkeye 3