for...of
语句在可迭代对象(包括 Array
,Map
,Set
,String
,TypedArray
,arguments 对象等等)上创建一个迭代循环,调用自定义迭代钩子,并为每个不同属性的值执行语句
Symbol.iterator 为每一个对象定义了默认的迭代器。该迭代器可以被 for...of
循环使用。
以下可以迭代的类型,都有Symbol.iterator 属性。
注意iterator接口可以调用next方法,与Symbol.iterator不同!!!
一、可迭代类型
1、迭代遍历数组
let arr = [10,20,30,40];
let result = [];
for(let value of arr) {
result.push(value);
}
console.log(result); [10, 20, 30, 40]
数组的原型上有该属性
2、迭代遍历字符串
let str = "abcd";
let result = [];
for(let value of str) {
result.push(value);
}
console.log(result); ["a", "b", "c", "d"]
字符串的原型上有该属性
3、迭代遍历arguments
let result = [];
function arg(){
for(let value of arguments) {
result.push(value);
}
console.log(result); [1, "a", true]
}
arg(1,"a",true);
arguments中有Symbol.iterator
类数组是不可以进行迭代的
因为类数组上没有Symbol.iterator 属性,它的原型(是Object)也是没有Symbol.iterator 属性的。
类数组可以调用Array.from方法,而不能通过for of迭代
let result = [];
let obj = {0:"a",1:"b",2:"c",length:3};
console.log(Array.from(obj)); 类数组可以调用Array.from方法 ["a", "b", "c"]
for(let value of obj) {
result.push(value); 报错obj is not iterable
}
console.log(result);
迭代遍历Map对象
let result = [];
let myMap = new Map();
myMap.set(1,"a").set(true, "b").set([1,2],"c");
for(let value of myMap) {
result.push(value);
}
console.log(result);
迭代遍历Set对象
let result = [];
let mySet = new Set();
mySet.add("a").add(1).add(true);
for(let value of mySet) {
result.push(value);
}
console.log(result); ["a", 1, true]
迭代遍历类型数组
let result = [];
let int8 = new Int8Array(4);
int8[0] = 1;
int8[1] = 10;
int8[2] = 20;
int8[3] = 30;
for(let value of int8) {
result.push(value);
}
console.log(result); [1, 10, 20, 30]
迭代遍历生成器:
。。。
迭代一个自定义的可迭代对象:
。。。
二、for of 和for in的区别
for...of
语句遍历可迭代对象定义要迭代的数据。
1、for of迭代器中也可以用continue和break,与for循环中的效果一样。
(1)break跳出循环
let arr = [10,20,30,40];
let result = [];
for(let value of arr) {
if(value == 30){
break;
}
result.push(value);
}
console.log(result); [10, 20]
(2)continue跳过本次循环
let arr = [10,20,30,40];
let result = [];
for(let value of arr) {
if(value == 30){
continue;
}
result.push(value);
}
console.log(result); [10, 20, 40]
以下示例显示了与Array
一起使用时,for...of
循环和for...in
循环之间的区别。
注意:
注意for in会往原型链上进行查看的,注意看属性的顺序
注意数组上也可以添加属性和属性值,但不能被for of迭代到,而可以被for in遍历到。新添加的值,可以被for of迭代。
Object.prototype.objCustom = function() {};
Array.prototype.arrCustom = function() {};
let iterable = [3, 5, 7];
iterable.foo = 'hello';
iterable.push("a");
for (let i in iterable) {
console.log(i); 0, 1, 2, 3 "foo", "arrCustom", "objCustom"
}
for (let i in iterable) {
if (iterable.hasOwnProperty(i)) {
console.log(i); 0, 1, 2, 3 "foo"
}
}
for (let i of iterable) {
console.log(i); 3, 5, 7, "a"
}
console.log(iterable); [3, 5, 7, "a", foo: "hello"]