for,foreach,forin,forof用法和区别

demo.js

var arrayList = [{ id: 1, name: "zs", scope: 56 },
{ id: 2, name: "ls", scope: 86 },
{ id: 3, name: "wu", scope: 22 },
{ id: 4, name: "cl", scope: 42 },
{ id: 5, name: "qb", scope: 64 },
];

/* 
    普通for循环
    for循环中可以使用return、break等来中断循环
*/
function forLoop() {
    for (let index = 0; index < arrayList.length; index++) {
        const element = arrayList[index];
        console.log("for-index:", index);
        console.log("for-element:", element);
    }
}

/* 
    for-each
    arr.forEach(callback(currentValue [, index [, array]])[, thisArg])
    不能使用return、break等中断循环,不改变原数组
    https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach
*/
function forEachLoop() {
    arrayList.forEach((element, index) => {
        console.log('for-each-index:', index);
        console.log('for-each-element:', element);
    });
}

/* 
    for-in
    for ... in是为遍历对象属性而构建的,循环遍历的值都是数据结构的键值(key,value),不建议与数组一起使用
    https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Statements/for...in
*/
function forInLoop() {
    var obj = { id: 5, name: "qb", scope: 64 };
    for (const key in obj) {
        console.log('for-in-key:', key);// obj = {key:value}
        // 读取value
        if (Object.hasOwnProperty.call(obj, key)) {
            const value = obj[key];
            // console.log('for-in-value:', value);
        }
    }
}

/* 
    for-of
    它是ES6中新增加的语法,用来循环获取一对键值对中的值,循环一个普通对象会报错
    for...of语句在可迭代对象(包括 Array,Map,Set,String,TypedArray,arguments 对象等等)上创建一个迭代循环,调用自定义迭代钩子,并为每个不同属性的值执行语句
    https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Statements/for...of
*/
function forOfLoop() {
    var obj = { id: 5, name: "qb", scope: 64 };

    for (const iterator of arrayList) {
        console.log('for-of-iterator:', iterator);
    }
}

forLoop();
console.log('---------------------------------------');
forEachLoop();
console.log('---------------------------------------');
forInLoop();
console.log('---------------------------------------');
forOfLoop();
console.log('---------------------------------------');

posted @ 2022-03-30 17:32  sunshine233  阅读(145)  评论(0编辑  收藏  举报