[英]Coffeescript - how do I check string equality when passing string through a splat?
I'm having trouble checking whether two strings are equal when one of them was passed through a splat argument. 我很难检查两个字符串中的一个通过splat参数传递时是否相等。 Because coffeescript uses strict comparisons, and because it makes a copy of the arguments when they go through a splat, I can't get the strings to compare properly without resorting to backticks.
因为coffeescript使用严格的比较,并且由于它们在经过splat时会复制参数,所以我无法不借助反引号就无法正确比较字符串。 Is there a better way?
有没有更好的办法? Here's a minimal piece of code that demonstrates the problem:
这是演示该问题的最少代码:
check=(arg) ->
if arg == 'foo' then "'#{arg}'=='foo'" else "'#{arg}'!='foo'"
emit=(args...) ->
check(args)
console.log(emit('foo'))
console.log(check('foo'))
The output from this will be as follows: 其输出如下:
> coffee mincase.coffee
'foo'!='foo'
'foo'=='foo'
EDIT: mu is too short gave me the key, so the revised working code looks like this (everything is the same except emit) 编辑:亩太短给了我钥匙,所以修改后的工作代码看起来像这样(除了发射,其他都一样)
emit=(args...)->
check.apply(null,args)
When you use a splat, the splat puts the splatted arguments into an array. 使用splat时,splat会将splatted参数放入数组中。 For example:
例如:
f = (x...) -> console.log(x instanceof Array)
f(6)
will give you a true
in the console. 在控制台中将为您提供
true
的信息。 The fine manual isn't so fine in this case, it doesn't exactly spell it out, it assumes that you understand how JavaScript's arguments
object works and leaves out the explicit splat puts your arguments into an array part. 好的手册在这种情况下不是很好,它没有完全将其拼写出来,它假定您了解JavaScript的
arguments
对象是如何工作的,并且省略了显式splat将您的参数放入数组部分。
So you end up passing an array to check
and an array compared with a string using CoffeeScript's ==
(or JavaScript's ===
) will never be true. 因此,您最终要传递一个数组进行
check
并且使用CoffeeScript的==
(或JavaScript的===
)将一个与字符串进行比较的数组永远都不是正确的。
If you want emit
to check the first argument, then you need to say so: 如果您要
emit
检查第一个参数,则需要这样说:
emit = (args...) -> check(args[0])
Demo: http://jsfiddle.net/ambiguous/TBndM/ 演示: http : //jsfiddle.net/ambiguous/TBndM/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.