简体   繁体   中英

passing arguments to foreach loop

I'm trying to pass an argument through an .each function, but can't seem to do so. Yet, before the .each statement, the argument has a value, but I can't get to it from within said statement.

code

show: function (new_value) {
    console.log( new_value )        // returns proper information
    $('span[data-xyz]').each(function () {
        console.log( new_value )    // returns `undefinded`

        var attribute = $(this).attr("data-xyz");
        if(typeof new_value === "undefined")
            var new_value = system.defaults.xyz;

        console.log( new_value )    // returns `system.defaults.xyz`

        $(this).text(attribute[new_value]);
    }
}

How can I get new_value to be received in my .each statement ?

This line

var new_value = system.defaults.xyz

declares a local variable inside the the each callback. The variable doesn't have a value until this line is executed, that's why you get undefined .

If you don't want to declare a new variable, but rather reference the new_value variable from the outer function, drop the var keyword.

Learn more about hoisting .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM