Array遍历

175 阅读1分钟

** Array遍历 **

  • for循环
const array = [1, 2, 3, 4, 5];
for (let index = 0; index < array.length; index++) {
    if (index === 2) {
        break;
    }
    console.log(array[index]);
}

ES5

  • forEach(不能使用continue与break)
const array = [1, 2, 3, 4, 5];
array.forEach(item => {
    if (item == 2) {
        break;//Uncaught SyntaxError: Illegal break statement
    }
    console.log(item);
});
  • every(默认返回false,进行遍历的话,return true)
//break
const array = [1, 2, 3, 4, 5];
array.every(item => {
    if (item === 4) {
        return false;
    } else {
        console.log(item);
        return true;
    }
});
//continue
const array = [1, 2, 3, 4, 5];
array.every(item => {
    if (item === 4) {
    } else {
        console.log(item);
        return true;
    }
});
  • for in
    条件:对象,并且是遍历的
    原理:检查属性在对象中是否存在,同样会查找对象的整条原型链(w无论属性是否可枚举)
const array = [1, 2, 3, 4, 5];
array.a = 8;
array["b"] = 2;
array["5"] = 21;
console.log(array.length); //6
for (const key in array) {
	if (key == 2) {  //key是string
        break;
    }
    console.log(key, array[key]);
}

ES6之后

  • for of(除了数组与Object需要遍历的对象,用这个方法=)