将本地数组值导出为全局值

export local array value to global value

我正在尝试 return 数组的值,方法是使用 console.log(array);它 return 空值 []。非常感谢任何建议。

var array = [];
var maxLength = 3;
var delay = 250; //I shortened your delay
var ticker = {}; //I'll use this to simulate your ticker object

var looper = setInterval(function() { 
      ticker.BNBBTC = Math.random(); //populating your ticker property w/random value

      if (array.length < maxLength) {
         array.push(ticker.BNBBTC);
      } else {
         console.log("Stopping the looper.");
         clearInterval(looper);
         console.log("Here are the contents of array");
         console.log(array);
      }
}, delay);

以下是使用回调的方法

const fn = callback => {
  var array = [];
  var maxLength = 3;
  var delay = 250; //I shortened your delay
  var ticker = {}; //I'll use this to simulate your ticker object

  var looper = setInterval(function() {
    ticker.BNBBTC = Math.random(); //populating your ticker property w/random value

    if (array.length < maxLength) {
      array.push(ticker.BNBBTC);
    } else {
      console.log("Stopping the looper.");
      clearInterval(looper);
      console.log("Here are the contents of array");
      callback(array);
    }
  }, delay);
};
fn(result => {
  console.log(result);
})

或承诺

const fn = () => new Promise(resolve => {
  var array = [];
  var maxLength = 3;
  var delay = 250; //I shortened your delay
  var ticker = {}; //I'll use this to simulate your ticker object

  var looper = setInterval(function() {
    ticker.BNBBTC = Math.random(); //populating your ticker property w/random value

    if (array.length < maxLength) {
      array.push(ticker.BNBBTC);
    } else {
      console.log("Stopping the looper.");
      clearInterval(looper);
      console.log("Here are the contents of array");
      resolve(array);
    }
  }, delay);
});
fn().then(console.log)

您会注意到,使用这两种方法都没有理由“污染”全局名称空间 - 在现代 javascript 中您应该尽可能避免这种情况 - 在这两种情况下唯一的全局名称空间是const fn