如何在函数外使用函数中定义的变量?

时间:2017-09-19 06:01:43

标签: javascript

这是我的代码:

function gotData(data) {
  console.log(data.val())
  var promotions = data.val()
  var keys = Object.keys(promotions)
  console.log(keys)
  for (var i = 0; i < keys.length; i++) {
    var k = keys[i]
    var name = promotions[k].promotionName
    var description = promotions[k].description
    var validityFrom = promotions[k].validityPeriodFrom
    var validityTo = promotions[k].validityPeriodTo
    var dateCreated = promotions[k].dateCreated
    var dateUpdated = promotions[k].dateUpdated
  }
}

如何访问我的gotData函数之外的变量name,description,validityFrom,validityTo,dateCreated和dateUpdated?

2 个答案:

答案 0 :(得分:0)

在函数范围内定义的变量不能是该函数的本地变量,并且当您离开该函数时不再存在,如果您希望它们持久存在然后在函数外部创建它们,使它们全局或通过在对象中并使用这两种方法填充对象,您可以访问函数内部修改的数据。

    function gotData(data, aryResults) {
      if ( typeof aryResults != "object" ) {
        console.log("'aryResults' must be declared as []");
        return;
      }
      console.log(data.val());
      var promotions = data.val();
      var keys = Object.keys(promotions);
      console.log(keys);
      for( var i=0; i<keys.length; i++ ) {
        var k = keys[i];
        aryResults.push({name:promotions[k].promotionName
                 ,description:promotions[k].description
                ,validityFrom:promotions[k].validityPeriodFrom
                  ,validityTo:promotions[k].validityPeriodTo
                 ,dateCreated:promotions[k].dateCreated
                 ,dateUpdated:promotions[k].dateUpdated});
      }
    }

aryResults是一个包含所有提取数据的数组。

答案 1 :(得分:-1)

您需要创建一个全局变量并使用它

var globalvar = [];

function gotData(data) {
  console.log(data.val())
  var promotions = data.val()
  var keys = Object.keys(promotions)
  console.log(keys)
  for (var i = 0; i < keys.length; i++) {
    var k = keys[i]
    globalvar.name = promotions[k].promotionName
    globalvar.description = promotions[k].description
    globalvar.validityFrom = promotions[k].validityPeriodFrom
    globalvar.validityTo = promotions[k].validityPeriodTo
    globalvar.dateCreated = promotions[k].dateCreated
    globalvar.dateUpdated = promotions[k].dateUpdated
  }
}

然后您可以使用此变量调用如下。

globalvar.name
globalvar.description
globalvar.validityFrom 
globalvar.validityTo
globalvar.dateCreated
globalvar.dateUpdated