在循环内使用函数是否正确

时间:2018-07-22 07:52:51

标签: javascript json node.js

我想知道在循环内调用函数是一种好习惯,下面的两个代码,具有相同的结果,但是我想弄清楚,这就是为什么我要使用函数,是使用的一种好习惯?谢谢

无功能:

var json = {
    "lists": [
        {
            "items": [
                {
                    "one": "one",
                    "two": "two"

                }
            ]
        }
    ]
};

json.lists.forEach(function (list) {
    list.items.forEach(function (item) {
        console.log(item);
    })
});

结果:{一个:“一个”,两个:“两个”}

具有功能:

var json = {
    "lists": [
        {
            "items": [
                {
                    "one": "one",
                    "two": "two"

                }
            ]
        }
    ]
};

function getItem(list) {
    list.items.forEach(function (item) {
        console.log(item);
    })
}

json.lists.forEach(function (list) {
    getItem(list)
});

结果:{一个:“一个”,两个:“两个”}

1 个答案:

答案 0 :(得分:1)

为了获得更好的调试功能,不建议使用匿名函数。因此,请不要使用它们:

    var json = {
    "lists": [
        {
            "items": [
                {
                    "one": "one",
                    "two": "two"

                }
            ]
        }
    ]
};

    function logSingleItem(item) {
        console.log(item);
    }

    function loopListItem(list) {
        list.items.forEach(logSingleItem)
    }

    json.lists.forEach(loopListItem);