Javascript code execution order strangeness

你。 提交于 2019-12-22 08:07:17

问题


I have a section of Javascript/Coffeescript that seems to be executing out of order.

console.log list
console.log list[card_number]
if list[card_number]
  console.log "MATCHES"
  new_card = list[card_number]
else
  console.log "NO MATCHES"
  new_card = create_new_card(card_number)

create_new_card: (card_number) ->
  new_card =
    card_number: card_number
  list[new_card.card_number] = new_card
  return new_card

Every time I run this, the first console.log shows a list of cards that includes the new_card, Even if the card hasn't been created yet. Then it ALWAYS hits the else, no matter how many times it is run.

If I attempt to run list[<card_number>] in the Javascript console after this code runs, I receive the proper object, but each time the code runs on it's own, the same event happens.


回答1:


In google chrome, if you want to log objects with the state they had at the time of logging, you need to log a clone object or just stringify it.

var a = [];
console.log(a);
a[0] = 3;

Will log [3] because it logs a live object, while this will log []:

var a = [];
console.log(JSON.parse(JSON.stringify(a)));
a[0] = 3;

It is also a live object logging but it is a throwaway clone that was cloned at the point in time when a didn't have any items.

This is not related to the possible logical errors in your code that @CallumRogers pointed out.




回答2:


Your create_new_card function is wrong - you call new_card.number instead of new_card.card_number which always results in undefined being added to the list resulting the behaviour that you have observed. The correct version is:

create_new_card: (card_number) ->
  new_card =
    card_number: card_number
  list[new_card.card_number] = new_card
  return new_card



回答3:


Are you using Chrome? console.log does not execute immediately. Its a shame, but too bad for us.



来源:https://stackoverflow.com/questions/9136415/javascript-code-execution-order-strangeness

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!