简体   繁体   中英

Access value outside of for-loop in Javascript

Hi!

By iterating through nested json-files I'm using this function:

function buildPeopleGroups(People, container, parentObject) {
    _.each(People, function (item) {

        var peopleGuid =[];
        for (var peopleIterator= 0; peopleIterator< People.length; peopleIterator++) {
            peopleGuid [peopleIterator] = People[peopleIterator].Id
        }
        var newContainer;
        item.parent = parentObject;
        //switch different people
        switchPeople(item.Name, parentObject, peopleGuid [peopleIterator]);
        if (item.People) buildPeopleGroups(item.People, container, item);
    });
};

But this doesnt work... The 'peopleGuid [peopleIterator]'-attribute is out of scope and cannot be accessed outside of the for-loop. Now how can I easily put this value into the 'switchPeople'-function? Thanks in advance!

try this way

 var peopleGuid =[];
    for (var peopleIterator= 0; peopleIterator< People.length; peopleIterator++) {
        peopleGuid.push({peopleIterator:People[peopleIterator].Id});
    }
 console.log('peopleGuid',peopleGuid);

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