简体   繁体   English

Coffescript / Javascript类型的差异

[英]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: 这个Coffescript代码表现得很奇怪:

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. 我也会第一次将字符串扩展到那里。当我将CS代码传递到coffeescript.org时,我当然得到了JS代码。 But if I run that in jsfiddle, I get the expected result twice!... I cannot see what the difference is... 但是,如果我在jsfiddle中运行它,我会两次获得预期的结果!...我看不出有什么区别...

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? 1)为什么我没有在第一个循环中获取“字符串”日志,以及2)为什么/ do /我进入了解释的JS,却没有进入jsfiddle的CS解释器?

the origional CS code: CS code in fiddle 原始CS代码: 提琴中的CS代码

the interpreted JS code: JS code in fiddle 解释后的JS代码: 提琴中的JS代码

Willing to learn, but stumped for the moment... :-) 愿意学习,但暂时陷入困境... :-)

Your CS has a tab 您的CS有一个标签

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);

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

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