为什么CoffeeScript在地图后需要空格? [英] Why does CoffeeScript require whitespace after map?

查看:89
本文介绍了为什么CoffeeScript在地图后需要空格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码

  nums = [1..10] .map(i) i * 2 

运行



  nums = [1..10] .map(i) i * 2 

已损坏

解决方案

这样做的原因是函数调用(调用)的括号是可选的。我发现这是我自己的代码中的一个常见的混乱,并有一个通用的政策,总是包括括号,以表明。



在咖啡脚本,如果你省略括号假定参数列表到行的结尾。您的第一个示例咖啡脚本实际上与此相同:

  nums = [1..10] .map - > i * 2)

其中映射调用的第一个参数是一个函数(i) - > i * 2



如果您删除地图和(i)脚本在行的其余部分表示括号。您的第二个示例咖啡脚本实际上与此相同:

  nums = [1..10] .map - > i * 2)

在这里你可以看到地图被调用 i 作为唯一的参数,然后coffee脚本期待 map(i)调用返回一个函数, code> - > i * 2 或更明确的() - > i * 2 p>

由于咖啡脚本旨在消除javascript的潜在编码危险,我认为如果没有包含这个暗示的括号,它会更加安全。


This code

nums = [1..10].map (i) -> i*2

Runs

Whereas this

nums = [1..10].map(i) -> i*2

is broken

解决方案

The reason for this is that parentheses for a function call (invocation) are optional. I find this a constant confusion in my own code and have a general policy of always including parentheses to make it clear.

In coffee script, if you leave out the parentheses it assumes that the argument list goes to the end of the line. Your first example coffee script is actually the same as this:

nums = [1..10].map((i) -> i*2)

where the first argument of the call to map is a function (i)->i*2

If you remove the space between the map and the (i) then coffee script implies parentheses around the rest of the line. Your second example coffee script is actually the same as this:

nums = [1..10].map(i)(-> i*2)

Here you can see that map is being called with i as the only argument and then coffee script is expecting the map(i) call to return a function which is then being called passing ->i*2 or to be more explicit ()->i*2 as an argument.

Given that coffee script is designed to remove the potential coding hazards of javascript, I think that it would have been much safer if they had not included this implied parenthesis.

这篇关于为什么CoffeeScript在地图后需要空格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆