Javascript code execution order

I have a Javascript / Coffeescript section that doesn't seem to work.

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 

Each time I run this, the first console.log shows a list of maps that include the new_card, even if the map has not been created yet . Then it ALWAYS ends up in else , no matter how many times it starts.

If I try to run list[<card_number>] in the Javascript console after running this code, I get the corresponding object, but every time the code is executed on it, the same event occurs.

+4
source share
3 answers

In google chrome, if you want to register objects with the state that they had during logging, you need to register a clone object or just reinforce it.

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

It will keep a log [3] because it registers a living object, whereas it will log [] :

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

It is also a record in a real object, but it is a cloned clone that was cloned at a point in time when a had no elements.

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

+5
source

Your create_new_card function is incorrect - you call new_card.number instead of new_card.card_number , which always results in adding undefined to the list, as a result of which you observed the behavior. 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 
+1
source

Are you using Chrome? console.log not running immediately . This is a shame, but too bad for us.

+1
source

Source: https://habr.com/ru/post/1394707/


All Articles