在Javascript中访问for循环之外的值

时间:2017-08-17 09:52:51

标签: javascript arrays json

你好!

通过迭代嵌套的json文件我使用此函数:

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);
    });
};

但这不起作用......人员指南[peopleIterator]&#39; -attribute超出了范围,无法在for循环之外访问。现在我怎样才能轻松地将这个值放入&switch?人体功能? 提前谢谢!

1 个答案:

答案 0 :(得分:0)

试试这种方式

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