简体   繁体   English

在父函数之外使用数组

[英]use array outside the parent function

with this function triggered as a callback 该函数作为回调触发

 var testing  = []; 
 var vid;

function showMyVideos(data){

        var feed = data.feed; //object "feed"
        var entries = feed.entry || [];   //array "entry"
        var html = ['<ul>'];
        for (var i = 0; i < entries.length; i++){
            entry = entries[i];
            playCount = entry.yt$statistics.viewCount.valueOf() + ' views';
            title = entry.title.$t;

            vid = (getVideoId(entry.link[0].href));
            testing[i] = vid;
            lnk = '<a href = \'' + entry.link[0].href + '\'>link</a>';
            html.push('<li>', title, ', ', playCount, ', ', vid, ', ', lnk, '</li>');

        }
        html.push('</ul>');
        $('#videoResultsDiv').html(html.join(''));


     }

I want to use the "testing" array on other functions, how will I do that?.. I'm frustrated now, sorry I'm just starting to appreciate JavaScript. 我想在其他函数上使用“测试”数组,我该怎么做?..我现在很沮丧,对不起,我才刚刚开始欣赏JavaScript。 I want to perfectly access the array data like when I'm doing on console.log(testing) inside the function.. 我想完美地访问数组数据,就像在函数内的console.log(testing)上进行操作时一样。

"testing" is in the global scope and it should be accesible anywhere as long as there isn't another variable in another scope with the same name overriding the global "testing". “测试”在全局范围内,只要在另一个范围内没有另一个具有相同名称的变量覆盖全局“测试”,它就可以在任何地方使用。

If the values aren't accesible in the place you are trying it, it could be because that function is getting executed before the callback loads the values in "testing". 如果这些值在您尝试使用的地方不可接受,则可能是因为该函数在回调加载“测试”中的值之前被执行。

As has been mentioned testing is global scope, so you can use it anywhere. 如前所述, testing是全局范围的,因此您可以在任何地方使用它。 So it's important that you have the correct execution order for the functions using testing . 因此,对于使用testing的功能,您必须具有正确的执行顺序,这一点很重要。

Some might frown on using global scope in javascript but there are ways to mitigate issues. 有些人可能不愿在javascript中使用全局作用域,但是有缓解问题的方法。

Generally when I have to implement global scope vars, I will create a method along the lines of 'clear_session' or 'reset_globals'. 通常,当我必须实现全局范围var时,我将按照“ clear_session”或“ reset_globals”的方式创建一个方法。

In your case a function like that would look like this: 在您的情况下,类似的函数将如下所示:

function reset_globals(){
   testing  = []; 
   vid;
}

This is useful because then you know that after you call reset_globals() that your variables are going to be empty. 这很有用,因为这样您便知道在调用reset_globals() ,变量将为空。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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