Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/69.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 访问在函数内部的for循环中创建的变量_Javascript_Jquery - Fatal编程技术网

Javascript 访问在函数内部的for循环中创建的变量

Javascript 访问在函数内部的for循环中创建的变量,javascript,jquery,Javascript,Jquery,所以我得到了这个脚本,它在for循环中创建变量,它在不同的函数中。我在这里讨论这些变量,试图缩短它们,下面是完整的代码 for(var i = 0; i < max; i++){ var url = "https://www.instagram.com/p/" + imgs[i].node.shortcode, type_resource = "sidecar"; image = imgs[i].node.thumbnail

所以我得到了这个脚本,它在for循环中创建变量,它在不同的函数中。我在这里讨论这些变量,试图缩短它们,下面是完整的代码

      for(var i = 0; i < max; i++){
         var url = "https://www.instagram.com/p/" + imgs[i].node.shortcode,
         type_resource = "sidecar";
         image = imgs[i].node.thumbnail_resources[image_index].src;
         date = new Date(imgs[i].node.taken_at_timestamp * 1000);
         likes = imgs[i].node.edge_media_preview_like.count;
         comments = imgs[i].node.edge_media_to_comment.count;
      }
对全局变量使用window.variableName=variableValue,而不是var variableName=variableValue。请注意,应尽可能避免使用全局变量,而在较新的JS中,最好使用ES模块。

因为您使用的是var,所以需要阅读才能理解。对于var,For循环或任何其他非函数块都不是变量的作用域。它被提升到它所在的功能的顶部。另外,您实际上只声明了两个变量:url和type_resource。所有其他变量都是隐式全局变量,这是一个非常糟糕的想法。如果你真的打算使用全局搜索引擎,最好按照@nickmccurdy说的去做。
/*!
 * jquery.instagramFeed
 *
 * @version 1.2.7
 *
 * @author Javier Sanahuja Liebana <bannss1@gmail.com>
 * @contributor csanahuja <csanahuja10@gmail.com>
 *
 * https://github.com/jsanahuja/jquery.instagramFeed
 *
 */
(function($){
    var defaults = {
        'host': "https://www.instagram.com/",
        'username': 'username',
        'tag': '',
        'container': '#instagram',
        'display_profile': true,
        'display_biography': true,
        'display_gallery': true,
        'display_igtv': false,
        'get_data': false,
        'callback': null,
        'styling': true,
        'items': 8,
        'items_per_row': 4,
        'margin': 0.5,
        'image_size': 640
    };
    var image_sizes = {
        "150": 0,
        "240": 1,
        "320": 2,
        "480": 3,
        "640": 4
    };
    var escape_map = {
        '&': '&amp;',
        '<': '&lt;',
        '>': '&gt;',
        '"': '&quot;',
        "'": '&#39;',
        '/': '&#x2F;',
        '`': '&#x60;',
        '=': '&#x3D;'
    };
    function escape_string(str){
        return str.replace(/[&<>"'`=\/]/g, function (char) {
            return escape_map[char];
        });
    }

    $.instagramFeed = function(opts){
        var options = $.fn.extend({}, defaults, opts);
        if(options.username == "" && options.tag == ""){
            console.error("Instagram Feed: Error, no username or tag found.");
            return false;
        }
        if(typeof options.get_raw_json !== "undefined"){
            console.warn("Instagram Feed: get_raw_json is deprecated. See use get_data instead");
            options.get_data = options.get_raw_json;
        }
        if(!options.get_data && options.container == ""){
            console.error("Instagram Feed: Error, no container found.");
            return false;
        }
        if(options.get_data && options.callback == null){
            console.error("Instagram Feed: Error, no callback defined to get the raw json");
            return false;
        }

        var is_tag = options.username == "",
            url = is_tag ? options.host + "explore/tags/"+ options.tag + "/" : options.host + options.username + "/";

        $.get(url, function(data){
            try{
                data = data.split("window._sharedData = ")[1].split("<\/script>")[0];
            }catch(e){
                console.error("Instagram Feed: It looks like the profile you are trying to fetch is age restricted. See https://github.com/jsanahuja/InstagramFeed/issues/26");
                return;
            }
            data = JSON.parse(data.substr(0, data.length - 1));
            data = data.entry_data.ProfilePage || data.entry_data.TagPage;
            if(typeof data === "undefined"){
                console.error("Instagram Feed: It looks like YOUR network has been temporary banned because of too many requests. See https://github.com/jsanahuja/jquery.instagramFeed/issues/25");
                return;
            }
            data = data[0].graphql.user || data[0].graphql.hashtag;

            if(options.get_data){
                options.callback(data);
                return;
            }   

            //Setting styles
            var styles = {
                'profile_container': "",
                'profile_image': "",
                'profile_name': "",
                'profile_biography': "",
                'gallery_image': ""
            };
            if(options.styling){
                styles.profile_container = " style='text-align:center;'";
                styles.profile_image = " style='border-radius:10em;width:15%;max-width:125px;min-width:50px;'";
                styles.profile_name = " style='font-size:1.2em;'";
                styles.profile_biography = " style='font-size:1em;'";
                var width = (100 - options.margin * 2 * options.items_per_row)/options.items_per_row;
                styles.gallery_image = " style='margin:"+options.margin+"% "+options.margin+"%;width:"+width+"%;float:left;'";
            }

            var html = "";
            //Displaying profile
            if(options.display_profile){
                html += "<div class='instagram_profile'" +styles.profile_container +">";
                html += "<img class='instagram_profile_image' src='"+ data.profile_pic_url +"' alt='"+ (is_tag ? data.name + " tag pic" : data.username + " profile pic") +"'"+ styles.profile_image +" />";
                if(is_tag)
                    html += "<p class='instagram_tag'"+ styles.profile_name +"><a href='https://www.instagram.com/explore/tags/"+ options.tag +"' rel='noopener' target='_blank'>#"+ options.tag +"</a></p>";
                else
                    html += "<p class='instagram_username'"+ styles.profile_name +">@"+ data.full_name +" (<a href='https://www.instagram.com/"+ options.username +"' rel='noopener' target='_blank'>@"+options.username+"</a>)</p>";

                if(!is_tag && options.display_biography)
                    html += "<p class='instagram_biography'"+ styles.profile_biography +">"+ data.biography +"</p>";

                html += "</div>";
            }

            //image size
            var image_index = typeof image_sizes[options.image_size] !== "undefined" ? image_sizes[options.image_size] : image_sizes[640];

            if(options.display_gallery){
                if(typeof data.is_private !== "undefined" && data.is_private === true){
                    html += "<p class='instagram_private'><strong>This profile is private</strong></p>";
                }else{
                    var imgs = (data.edge_owner_to_timeline_media || data.edge_hashtag_to_media).edges;
                        max = (imgs.length > options.items) ? options.items : imgs.length;

                    html += "<div class='instagram_gallery'>";
                    for(var i = 0; i < max; i++){
                        var url = "https://www.instagram.com/p/" + imgs[i].node.shortcode,
                            image, type_resource, caption, date, likes, comments;


                        switch(imgs[i].node.__typename){
                            case "GraphSidecar":
                                type_resource = "sidecar"
                                image = imgs[i].node.thumbnail_resources[image_index].src;
                                date = new Date(imgs[i].node.taken_at_timestamp * 1000);
                                likes = imgs[i].node.edge_media_preview_like.count;
                                comments = imgs[i].node.edge_media_to_comment.count;
                                break;
                            case "GraphVideo":
                                type_resource = "video";
                                image = imgs[i].node.thumbnail_src
                                break;
                            default:
                                type_resource = "image";
                                image = imgs[i].node.thumbnail_resources[image_index].src;
                                date = new Date(imgs[i].node.taken_at_timestamp * 1000);
                                likes = imgs[i].node.edge_media_preview_like.count;
                                comments = imgs[i].node.edge_media_to_comment.count;
                        }
                                console.log(date);
                                console.log(likes);
                                console.log(comments);

                        if(
                            typeof imgs[i].node.edge_media_to_caption.edges[0] !== "undefined" && 
                            typeof imgs[i].node.edge_media_to_caption.edges[0].node !== "undefined" && 
                            typeof imgs[i].node.edge_media_to_caption.edges[0].node.text !== "undefined" && 
                            imgs[i].node.edge_media_to_caption.edges[0].node.text !== null
                        ){
                            caption = imgs[i].node.edge_media_to_caption.edges[0].node.text;
                        }else if(
                            typeof imgs[i].node.accessibility_caption !== "undefined" && 
                            imgs[i].node.accessibility_caption !== null
                        ){
                            caption = imgs[i].node.accessibility_caption;
                        }else{
                            caption = (is_tag ? data.name : data.username) + " image " + i;
                        }

                        html += "<a id='instagramID" + i + "' class='instagramimg instagram-" + type_resource + "' rel='noopener' target='_blank'>";
                        html += "<img class='instagramicon' src='https://cdn.shopify.com/s/files/1/0278/9644/7113/files/instagram-icon.svg?v=1592246117' alt='instagramicon'>";
                        html += "<div class='instagramhover'></div>";
                        html += "<img src='" + image + "' alt='" + escape_string(caption) + "'"/* + styles.gallery_image*/ +" />";
                        html += "</a>";
                    }

                  }
                }


            if(options.display_igtv && typeof data.edge_felix_video_timeline !== "undefined"){
                var igtv = data.edge_felix_video_timeline.edges,
                    max = (igtv.length > options.items) ? options.items : igtv.length
                if(igtv.length > 0){
                    html += "<div class='instagram_igtv'>";
                    for(var i = 0; i < max; i++){
                        html += "<a href='https://www.instagram.com/p/"+ igtv[i].node.shortcode +"' rel='noopener' target='_blank'>";
                        html += "<img src='"+ igtv[i].node.thumbnail_src +"' alt='"+ options.username +" instagram image "+ i+"'"+styles.gallery_image+" />";
                        html += "</a>";
                    }
                    html += "</div>";
                }
            }

            $(options.container).html(html);
        }).fail(function(e){
            console.error("Instagram Feed: Unable to fetch the given user/tag. Instagram responded with the status code: ", e.status);
        });

        return true;
    };

})(jQuery);