Javascript - scope of nested for loop index

后端 未结 3 1734
一向
一向 2021-01-05 19:03

I remember variables are function scoped in Javascript. But, how is the behavior if I redefine the local variable in a loop. One common use case is nested loops. In the bel

3条回答
  •  無奈伤痛
    2021-01-05 19:27

    There's no block level scope in JS.

    But if it's utmost necessary to have/re-declare the same variable name in your code, you can do:

    function loopIt(arr, fn, scope) {
        for (var i = 0, len = arr.length; i < len; i++) {
            fn.call(scope || this, arr[i], i, arr);
        }
    }
    

    And use it like:

    var firstArr = ["a", "b"];
    var secondArr = ["c", "d"];
    
    loopIt(firstArr, function(item, i) {
        var msg = "Hey it's '" + item + "'";
        console.log(msg);
    
        // if you want access to the parent scope's var
        var scopedItem = item;
    
        loopIt(secondArr, function(item, i) {
            var msg = "Hello it's '" + item + "' in '" scopedItem + "'";
            console.log(msg);
        });
    });
    

    That will give us results of:

    Hey it's 'a'
    Hello it's 'c' in 'a'
    Hello it's 'd' in 'a'
    Hey it's 'b'
    Hello it's 'c' in 'b'
    Hello it's 'd' in 'b'
    

提交回复
热议问题