美文网首页
for,for in,forEach,for of 各种循环的用

for,for in,forEach,for of 各种循环的用

作者: 微志异 | 来源:发表于2019-02-22 08:59 被阅读14次

for循环

const ary = [10, 20, 30];
for(let i = 0, len = ary.length; i < len; i++) {
    console.log(ary[i]);
}
// 10
// 20
// 30

for...in循环

此语句以任意顺序遍历一个对象的可枚举属性。

const person = {
    firstName: "Jon",
    age:18
};
for(let info in person) {
    console.log(`person[${info}] = ${person[info]}`);
}
//person[firstName] = Jon
//person[age] = 18

注意:

  • for...in只能遍历对象的“可枚举的属性”

  • for-in遍历属性的顺序并不确定,因此数组迭代推荐使用for循环(或者使用 Array.prototype.forEach() 或 for...of 循环)

Array.prototype.forEach()

在ES5中引入了新的数组循环forEach对数组中的每个元素执行一次提供的函数。

该方法按升序为数组中含有效值的每一项执行一次callback 函数,那些已删除(使用delete方法等情况)或者未初始化的项将被跳过(但不包括那些值为 undefined 的项)。

function logArrayElements(element, index, array) {
    console.log("a[" + index + "] = " + element);
}

// 注意索引2被跳过了,因为在数组的这个位置没有项
[2, 5, ,9].forEach(logArrayElements);

// a[0] = 2
// a[1] = 5
// a[3] = 9

[2, 5,"" ,9].forEach(logArrayElements);
// a[0] = 2
// a[1] = 5
// a[2] = 
// a[3] = 9

[2, 5, undefined ,9].forEach(logArrayElements);
// a[0] = 2
// a[1] = 5
// a[2] = undefined
// a[3] = 9


let xxx;
// undefined

[2, 5, xxx ,9].forEach(logArrayElements);
// a[0] = 2
// a[1] = 5
// a[2] = undefined
// a[3] = 9

tTips:forEach第二个参数是可选参数,替代回调函数中的this值。

for...of语句

let iterable = [10, 20, 30];

for (let value of iterable) {
    value += 1;
    console.log(value);
}
// 11
// 21
// 31

注意:

  • 跟Array.prototype.forEach()相比,for...of可以正确响应break, continue, return,throw。

  • for...of不仅可迭代数组,还支持大多数类数组对象,例如DOM nodelist对象。还有其它可迭代对象(包括Map,Set,String,TypedArray,arguments对象等等)

  • for...of不支持普通对象,但如果你想迭代一个对象的属性,你还是用for-in循环吧

相关文章

网友评论

      本文标题:for,for in,forEach,for of 各种循环的用

      本文链接:https://www.haomeiwen.com/subject/tvksyqtx.html