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 (e.g., [{...},{...},{...}]
). However depending on the indentation level, the variable shows an empy array (i.e., []
).
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 a开发者_StackOverflowrray.
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)
精彩评论