简体   繁体   English

从JavaScript中的函数返回数组

[英]returning array from function in javascript

so I come from a heavy python background, and I'm trying to wrap my head around javascript. 因此,我来​​自浓郁的python背景,并且我想用javascript来解决问题。 Here I have a function that returns an array of track IDs for soundcloud songs by the artist 'v-2-followers'. 在这里,我有一个函数,用于返回艺术家'v-2-followers'的音云歌曲的音轨ID数组。 How would I go about assigning the output of SC.get(stuff) to a variable to reuse the track list in another function. 我将如何将SC.get(stuff)的输出分配给变量以在另一个函数中重用轨道列表。 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. 如果有人可以告诉我如何执行此操作,更重要的是,为什么要这样做,以备将来参考。

You have trackIdList as a global variable because it is not created using var . 您具有trackIdList作为全局变量,因为它不是使用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; 如果要将其范围限制为仅外部函数,请添加var trackIdList; as the first line of your function. 作为功​​能的第一行。 You should be declaring variables with var everywhere in order to limit their scope. 您应该在各处使用var声明变量,以限制其范围。

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

Further reading: What is the scope of variables in JavaScript? 进一步阅读: JavaScript中变量的范围是什么?

The other concept you need to understand is regarding asynchronous execution and callbacks in JavaScript. 您需要了解的另一个概念是关于JavaScript中的异步执行和回调。 Your code that populates trackIdList is contained within a callback function which is (most likely) called after your call to SC.stream() . 填充trackIdList代码包含在一个回调函数中,该回调函数很可能调用SC.stream() 之后被调用。 If SC.stream() depends on the value of trackIdList , it should be called from the callback function. 如果SC.stream()取决于价值trackIdList ,应该从回调函数被调用。

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() makes an asynchronous request and returns immediately. SC.get()发出异步请求并立即返回。 Then SC.stream() is called without waiting for the request to return . 然后SC.stream()而无需等待请求返回 processTracks() isn't called until the request comes back. 在请求返回之前,不会调用processTracks() The trouble is that SC.stream() depends on processTracks() , but is called immediately. 问题在于SC.stream()依赖于processTracks() ,但是被立即调用。 To fix this, call SC.stream() from the callback function of SC.get() : 要解决此问题,请从SC.stream()的回调函数中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();
        });
    }
})();

I'll explain one way - with callbacks. 我将解释一种方法-使用回调。 The reason people do it this way is that there are synchronous operations, and asynchronous operations. 人们这样做的原因是存在同步操作和异步操作。 In your case, you need to perform an AJAX request - we don't know how long it will take for SC.get to finish, and we don't want the program to hang while we wait for it. 在您的情况下,您需要执行AJAX请求-我们不知道SC.get完成需要多长时间,并且我们不希望程序在等待时挂起。 So instead of waiting, we tell it "go get those tracks, and I'm passing you a function to call when you are done. In the meantime, I'm going to go on ahead with the rest of the program." 因此,我们不必等待它,而是告诉它“去获得这些音轨,在完成后,我将为您传递一个函数来调用。同时,我将继续执行该程序的其余部分。”

(function() {

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

  var getTracks = function(callback) {
    SC.get('/tracks', { q: 'v-2-followers' }, function(tracks) {
        trackIdList = [];
        tracks.forEach(function(track){
            trackIdList.push(track.id);
        });
        callback(trackIdList);
    });
  }

  // And use the variable here.
  var stream = function(trackIdList) {
    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();
        });
     });
   }
   getTracks(stream);
 })();

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

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