Paul Wiegers
Paul Wiegers

Reputation: 199

difference in Coffescript / Javascript typeof

I'm trying to parse a object recursively not knowing if the next element is a string or a next, nested object. I was thinking of doing this by looking at the typeof of the value; it would be a string or a object. But something strange is happening...

This Coffescript code is behaving strange:

c = (strLog) ->
  console.log strLog
console.clear()
c '------------'


translateDoc= (doc) ->
    c 'in translatedoc'
    for key,value of doc
        c key
        c typeof(value)
    return null

doc =
    str1: 'content1'
    str2: 'content2'    
    obj1:
        str3: 'content 4'
        str4: 'content 3'      

for key,value of doc
    c key
    c typeof(value)     

translateDoc(doc)  

this will give this output:

str1
str2
obj1
object
in translate doc
str1
string
str2
string
obj1
object

which puzzels me; I would have expexted the string's to be there the first time too... when I passed the CS code into coffeescript.org, I got of course the JS code. But if I run that in jsfiddle, I get the expected result twice!... I cannot see what the difference is...

1) why do I not get the "string"-log the first loop, and 2) why /do/ I get in the interpreted JS, but not in the CS interpreter of jsfiddle?

the origional CS code: CS code in fiddle

the interpreted JS code: JS code in fiddle

Willing to learn, but stumped for the moment... :-)

Upvotes: 0

Views: 40

Answers (1)

Roy J
Roy J

Reputation: 43899

Your CS has a tab

for key,value of doc
  c key
  c typeof(value)  # tab instead of leading space

which causes it to transpile into

for (key in doc) {
  value = doc[key];
  c(key);
}

c(typeof value);

Upvotes: 1

Related Questions