从javascript中的函数返回数组 [英] returning array from function in javascript

查看:51
本文介绍了从javascript中的函数返回数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我来自一个沉重的 python 背景,我试图将我的头围绕在 javascript 上.这里我有一个函数,它返回艺术家v-2-followers"的 soundcloud 歌曲的轨道 ID 数组.我将如何将 SC.get(stuff) 的输出分配给变量以在另一个函数中重用曲目列表.我确定我错过了一些基本的东西.我不是在寻找解释如何做到这一点的答案,而是更多地为什么这样做.

so I come from a heavy python background, and I'm trying to wrap my head around javascript. Here I have a function that returns an array of track IDs for soundcloud songs by the artist 'v-2-followers'. How would I go about assigning the output of SC.get(stuff) to a variable to reuse the track list in another function. I'm sure I'm missing something fundamental. I'm less looking for an answer that explains how to do this, but more why it's done like that.

也就是说,我也非常感谢如何.:)

That said I would also very much appreciate the how. :)

(function() {

    SC.initialize({
        client_id:'__CLIENTID__';
    });

    // Would like to set a variable equal to the output of
    SC.get('/tracks', { q: 'v-2-followers' }, function(tracks) {
        trackIdList = [];
        tracks.forEach(function(track){
            trackIdList.push(track.id);
        });
        return trackIdList;
    });

    // And use the variable here.
    SC.stream('/tracks/'+trackIdList[Math.floor(Math.random() * myArray.length)], function(sound) {
        sound.play();
        sound.pause();
        $('#fabrizio').hover(function(e){
            sound.resume();
        }, function(e){
            sound.pause();
        });
    });
})();

我可以看到我在这里遗漏了一些关于变量赋值和作用域或函数回调的基本知识.我已经筋疲力尽地浏览了有关该主题的文档.如果有人能告诉我如何做到这一点,更重要的是,为什么要这样做,以供将来参考.

I can see that I'm missing something fundamental about variable assignment and scope, or function callbacks here. I've exhausted myself skimming docs on the subject. If anyone can tell me how to do this, and more importantly, why it's done that way, for future reference.

推荐答案

您将 trackIdList 作为全局变量,因为它不是使用 var 创建的.因此,您已经可以从任何其他功能访问它.如果您想将其范围限制为外部函数,请将 var trackIdList; 添加为函数的第一行.您应该在任何地方使用 var 声明变量以限制其作用域.

You have trackIdList as a global variable because it is not created using var. So as it is, you can already access it from any other function. If you wanted to limit its scope to just the outer function, add var trackIdList; as the first line of your function. You should be declaring variables with var everywhere in order to limit their scope.

(function() {
    var trackIdList;
    ...
})();

进一步阅读:JavaScript 中变量的作用域是什么?

您需要了解的另一个概念是关于 JavaScript 中的异步执行和回调.填充 trackIdList 的代码包含在回调函数中,该回调函数(很可能)在您调用 SC.stream() 之后调用 .如果SC.stream()依赖于trackIdList的值,则应从回调函数中调用.

The other concept you need to understand is regarding asynchronous execution and callbacks in JavaScript. Your code that populates trackIdList is contained within a callback function which is (most likely) called after your call to SC.stream(). If SC.stream() depends on the value of trackIdList, it should be called from the callback function.

通过分离回调函数可能有助于说明发生了什么.

It may help to illustrate what's going on by separating out your callback functions.

(function () {
    var trackIdList = [];

    SC.initialize({
        client_id: '__CLIENTID__'
    });

    SC.get('/tracks', { q: 'v-2-followers' }, processTracks);

    var randomIndex = Math.floor(Math.random() * myArray.length);
    SC.stream('/tracks/' + trackIdList[randomIndex], processSound);

    function processTracks(tracks) {
        tracks.forEach(function (track) {
            trackIdList.push(track.id);
        });
    }

    function processSound(sound) {
        sound.play();
        sound.pause();
        $('#fabrizio').hover(function (e) {
            sound.resume();
        }, function (e) {
            sound.pause();
        });
    }
})();

SC.get() 发出异步请求并立即返回.然后 SC.stream() 被调用,无需等待请求返回.processTracks() 在请求返回之前不会被调用.问题在于SC.stream() 依赖于processTracks(),但会被立即调用.要解决此问题,请从 SC.get() 的回调函数中调用 SC.stream():

SC.get() makes an asynchronous request and returns immediately. Then SC.stream() is called without waiting for the request to return. processTracks() isn't called until the request comes back. The trouble is that SC.stream() depends on processTracks(), but is called immediately. To fix this, call SC.stream() from the callback function of SC.get():

(function () {
    SC.initialize({
        client_id: '__CLIENTID__'
    });

    SC.get('/tracks', { q: 'v-2-followers' }, processTracks);

    function processTracks(tracks) {
        var trackIdList = [];
        tracks.forEach(function (track) {
            trackIdList.push(track.id);
        });

        var randomIndex = Math.floor(Math.random() * myArray.length);
        SC.stream('/tracks/' + trackIdList[randomIndex], processSound);
    }

    function processSound(sound) {
        sound.play();
        sound.pause();
        $('#fabrizio').hover(function (e) {
            sound.resume();
        }, function (e) {
            sound.pause();
        });
    }
})();

这篇关于从javascript中的函数返回数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆