CoffeeScript 是否允许 JavaScript 风格的 == 相等语义?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7032398/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 22:45:31  来源:igfitidea点击:

Does CoffeeScript allow JavaScript-style == equality semantics?

javascriptcoffeescript

提问by Justin Morgan

I love that CoffeeScript compiles ==into the JavaScript ===operator. But what if you want the original JS ==semantics? Are they available? I've pored over the documentation and can't find anything enabling this.

我喜欢CoffeeScript 编译==成 JavaScript===运算符。但是如果你想要原始的 JS==语义呢?它们可用吗?我已经仔细阅读了文档,但找不到任何启用此功能的内容。

More generally, is there a way to inline plain JS into my CoffeeScript code so that the compiler doesn't touch it?

更一般地说,有没有办法将纯 JS 内联到我的 CoffeeScript 代码中,这样编译器就不会触及它?

I'd prefer to avoid editing the compiled JavaScript output, since I'm using Chirpyto auto-generate it in Visual Studio.

我宁愿避免编辑已编译的 JavaScript 输出,因为我使用Chirpy在 Visual Studio 中自动生成它。

回答by Facebook Staff are Complicit

As a possible extension to this, is there a way to inline blocks of regular JS into CoffeeScript code so that it isn't compiled?

作为对此的可能扩展,有没有办法将常规 JS 块内联到 CoffeeScript 代码中,使其不被编译?

Yes, here's the documentation. You need to wrap the JavaScript code in backticks (`). This is the only way for you to directly use JavaScript's ==in CoffeeScript. For example:

是的,这是文档。您需要用反引号 ( `)包装 JavaScript 代码。这是您==在 CoffeeScript 中直接使用 JavaScript 的唯一方法。例如:

CoffeeScript 源代码 [try it][试试看]
if `a == b`
  console.log "#{a} equals #{b}!"
编译的 JavaScript
if (a == b) {
  console.log("" + a + " equals " + b + "!");
}


The specific case of == null/undefined/void 0is served by the postfix existential operator ?:

具体情况== null/ undefined/void 0由后缀存在运营商提供服务?

CoffeeScript 源代码 [try it][试试看]
x = 10
console.log x?
编译的 JavaScript
var x;
x = 10;
console.log(x != null);
CoffeeScript 源代码 [try it][试试看]
# `x` is not defined in this script but may have been defined elsewhere.
console.log x?
编译的 JavaScript
var x;
console.log(typeof x !== "undefined" && x !== null);

回答by Tim Scollick

This isn't exactly the answer but this problem came up for me because jQuery's .text() was including whitespace and 'is' was failing in Coffeescript. Get around it by using jQuery's trim function:

这不完全是答案,但这个问题对我来说是因为 jQuery 的 .text() 包含空格,而 'is' 在 Coffeescript 中失败了。使用 jQuery 的 trim 函数绕过它:

$.trim(htmlText) is theExpectedValue