[英]CoffeeScript function call - parameters and brackets
Exists such a Javascript code:存在这样一个Javascript代码:
var re = /some_regex/g;
return re.exec(link.attr('href'))[0]
How to call this in CoffeeScript In CoffeeScript there is no need in brackets for parameters but there is another call of function in param.如何在 CoffeeScript 中调用它
I've tried:我试过了:
re = /some_regex/g
re.exec link.attr 'href' [0] # compile error: unexpected [
re.exec (link.attr 'href')[0] # javascript: re.exec((link.attr('href'))[0]);
re.exec (link.attr('href'))[0] # javascript: re.exec((link.attr('href'))[0]);
how to do this?这个怎么做? or I should make
或者我应该做
// adding new variable
temp = re.exec link.attr 'href'
temp[0]
The space after re.exec
is causing a problem, because it causes the CoffeeScript compiler to think that (link.attr('href'))[0]
is the argument. re.exec
之后的空格引起了问题,因为它导致 CoffeeScript 编译器认为(link.attr('href'))[0]
是参数。
The correct way to do this is to do it exactly like in JavaScript, with no space:执行此操作的正确方法是完全按照 JavaScript 执行此操作,没有空格:
re.exec(link.attr('href'))[0]
If you really badly want to use the no-parens syntax on this line, this would also work:如果你真的很想在这一行使用无括号语法,这也可以:
re.exec(link.attr 'href')[0]
(They compile to the same result) (它们编译成相同的结果)
Wouldn't this be clearer if you simply parenthesized the part that absolutely needs it, and do the rest in the most CoffeeScript-like-way?如果您只是将绝对需要它的部分用括号括起来,并以最类似于 CoffeeScript 的方式执行 rest,这会不会更清楚?
(re.exec link.attr 'href')[0]
or maybe even (if 'href' is just another attribute):甚至可能(如果“href”只是另一个属性):
(re.exec link.attr.href)[0]
or, better, yet, to be more clear, along the lines of what you suggested originally:或者,更好的是,更清楚的是,按照您最初的建议:
matches = re.exec link.attr.href
matches[0] // idiomatic to re.exec: first element is matched RE
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.