全局变量在函数上下文之外不可用

时间:2018-08-21 02:50:29

标签: javascript global

我遇到了在函数上下文之外无法使用全局变量(featureData)的问题。该代码通过两个变量orgID和tagID从api中提取故事,将故事数据推入数组featureData中。我可以使用console.log()featureData并看到所有东西都进入了数组,我只是不能在getStories()之外使用它。

我在这里想念什么?

谢谢

window.featureData = [];
featureOrgs = {
    "1" : { orgID: "9", tagID: "629420434", tagName: "KNS" },
    "2" : { orgID: "60", tagID: "607709680", tagName: "KNS" },
    "3" : { orgID: "103", tagID: "625745862", tagName: "KNS" }
};

// get story data from API
function getStories(key,value) { 

    jQuery.getJSON('{API URL & KEY REMOVED}&orgId=' + value.orgID + '&id=' + value.tagID, function(json) {

            // parse stories into featureData
            for(let i = 0, l = json.list.story.length; i < l; i++) {
                // get all other data...
                // get tags
                for(let z = 0, l = json.list.story[i].parent.length; z < l; z++) {
                    if ( json.list.story[i].parent[z].type == "tag" ){
                        tags += json.list.story[i].parent[z].title.$text + ",";
                    }

                }

                // add 'kns' tagged stories to featureData
                if( tags.includes("KNS") ){
                    featureData.push({id, title, byline, teaser, date, storyImage, storyLink, organization, organizationWebURI, primaryImageThumb, categories, tags});\
                }

                //
                // * featureData DATA *IS AVAILABLE* HERE
                //

            } // for

    }); // getJSON

} // getStories()

// for each featureOrgs item, get stories by tag
jQuery(function() {
    Object.entries(featureOrgs).forEach(
        ([key, value]) => getStories(key,value)
    );

        //
        // * featureData DATA *IS NOT* AVAILABLE HERE??
        //

});

0 个答案:

没有答案