【问题标题】:Questions about Coffeescript/Javascript conditional results关于 Coffeescript/Javascript 条件结果的问题
【发布时间】:2011-08-28 20:55:05
【问题描述】:

我有这个 Coffeescript:

console.log 'TEST'
console.log index
console.log (index is not 0)
console.log (index > 0)
unless index is 0
    console.log "passed test"

这是编译好的 Javascript:

console.log('TEST');
console.log(index);
console.log(index === !0);
console.log(index > 0);
_results.push(index !== 0 ? console.log("passed test") : void 0);

这是控制台输出

TEST
0
false
false
passed test
TEST
1
false
true
passed test

问题 1) 为什么index 为 1 时,(index is not 0) 会返回 false(index > 0) 返回 true 为 1,那为什么 (index is not 0) 不返回呢?

问题2)为什么index为0时unless index is 0测试通过?

【问题讨论】:

    标签: javascript coffeescript


    【解决方案1】:

    index 为1 时,为什么(index is not 0) 返回false(index > 0) 返回 true 为 1,那为什么 (index is not 0) 不返回呢?

    CoffeeScript 不使用is not 表示不等式,它使用!=isnt。通过查看编译后的代码,我们可以看到它实际上将(index is not 0) 解释为(index is (not 0))

    index 为 0 时,为什么 unless index is 0 测试通过?

    I tried it myself 测试没有通过。此行为可能是由您的测试代码中未包含在您的帖子中的某些内容引起的。

    【讨论】:

    • 没错。在 CoffeeScript 中将 is notisnt 混淆是一个常见的错误。
    【解决方案2】:

    这很繁琐:

    console.log(index === !0);
    

    它的处理方式与以下相同:

    console.log(index === (!0));
    

    0 是一个虚假常量,因此您可以将(!0) 替换为true。那么真正的代码是:

    console.log(index === true);
    

    所以它只会在 index 为布尔值 true 且没有类型强制的情况下记录“true”。

    【讨论】:

      猜你喜欢
      • 2011-09-17
      • 1970-01-01
      • 2019-05-29
      • 1970-01-01
      • 1970-01-01
      • 2019-05-10
      • 1970-01-01
      • 1970-01-01
      • 2020-03-21
      相关资源
      最近更新 更多