在javascript中调用函数外部的变量

时间:2017-09-13 08:21:34

标签: javascript variables

我是javascript和firebase的新手。我想问一下是否有机会在函数之外调用我的变量?

以下是我的示例代码:

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
    console.log(name, description, validityFrom, validityTo, dateCreated, dateUpdated)
  }
}

我可以在函数gotData之外调用name,description,validityFrom等吗?我很感激你的帮助。先感谢您! :)

1 个答案:

答案 0 :(得分:3)

将变量定义为全局变量

//above function
var name, description, validityFrom, validityTo, dateCreated, dateUpdated;
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]
    name = promotions[k].promotionName
    description = promotions[k].description
    validityFrom = promotions[k].validityPeriodFrom
    validityTo = promotions[k].validityPeriodTo
    dateCreated = promotions[k].dateCreated
    dateUpdated = promotions[k].dateUpdated
    console.log(name, description, validityFrom, validityTo, dateCreated, dateUpdated)
  }
}
// now you can access variables here
console.log(name, description, validityFrom, validityTo, dateCreated, dateUpdated)

修改

您可以创建一个数组来获取所有变量,因为您可能拥有多维数据

var objData = [];
function gotData (data) {

  console.log(data.val())
  var promotions = data.val()
  var keys = Object.keys(promotions)

  for (var i = 0; i < keys.length; i++) {
    var tempObj = [];
    var k = keys[i]
    tempObj['promotionName'] = promotions[k].promotionName;
    tempObj['description'] = promotions[k].description;
    tempObj['validityPeriodFrom'] = promotions[k].validityPeriodFrom;
    tempObj['validityPeriodTo'] = promotions[k].validityPeriodTo;
    tempObj['dateCreated'] = promotions[k].dateCreated;
    tempObj['dateUpdated'] = promotions[k].dateUpdated;

    objData.push(tempObj);
  }
  console.log(objData)
}