简体   繁体   English

CoffeeScript / JavaScript中的变量作用域

[英]Variable scoping in CoffeeScript/JavaScript

In the following code, I want to use the markers variable, which I expect to be an array of objects (eg, [{...},{...},{...}] ). 在下面的代码中,我想使用markers变量,我希望它是一个对象数组(例如[{...},{...},{...}] )。 However depending on the indentation level, the variable shows an empy array (ie, [] ). 但是,根据缩进级别,该变量显示一个empy数组(即[] )。

jQuery ->
  markers = []
  $.getJSON '/users.json', (data) ->
    for obj in data
      marker = {}
      marker =
        lastname: namify(obj.name)
        address: obj.address
      markers.push(marker)
    console.log("3rd level", markers) # It shows the array I want.
  console.log("2nd level", markers)   # "markers" shows an empty array.

My Expectation - populated array in the 2nd level. 我的期望 -在第二级中填充的数组。 Result - an empty array in the 2nd level. 结果 -第二级中的一个空数组。

How can I retrive the array as shown in the 3rd level when I'm at the 2nd level. 当我处于第二级时,如何获取第三级中所示的数组。

You are populating your array inside the callback function. 您正在回调函数中填充数组。 So it's populated after you print the result. 因此,在打印结果后将填充它。 Problem is not about scope, it is about order of execution. 问题不关乎范围,而是关乎执行顺序。

If you make a synchronous request you should see what you expect: 如果发出同步请求,则应该看到期望的结果:

jQuery ->
  markers = []
  $.ajax
    url: '/users.json'
    dataType: 'json'
    async: false
    success: (data) ->
      for obj in data
        marker = {}
        marker =
          lastname: namify(obj.name)
          address: obj.address
        markers.push(marker)
    console.log("3rd level", markers)
  console.log("2nd level", markers)

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

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