【问题标题】:JavaScript: if var? where var is no boolJavaScript:如果变量?其中 var 不是布尔值
【发布时间】:2016-10-12 19:14:06
【问题描述】:

videojs 播放器的一些代码我不理解:

if currentSrc?
    $(".video-js").replaceWith(
      "<div class='unsupported'><a href='#{currentSrc}'>Download</a></div>")

据我了解,currentSrc 必须是一个布尔值,以便在 if 语句中检查真假,但后来在链接中集成它是一个字符串。 if var? 是否仅检查 var 是否存在?这不是在 JS 中检查它的错误方法吗?

【问题讨论】:

  • 如果是字符串,它将使用字符串的长度来确定真/假。长度为 0 为假,其他一切为真。你可以试试这个: alert(("false" ? 'true' : "false"))
  • 我不认为这是一个有效的 JS
  • currentSrc 必须是 bool,JS 不一定会将值强制转换为 bool。 JS 不是类型化语言,会根据使用情况改变类型
  • @Liam 此代码与if a ? 1 类似,即Uncaught SyntaxError: Unexpected identifier(…)
  • 我是CoffeeScript

标签: javascript if-statement coffeescript boolean


【解决方案1】:

currentSrc 必须是一个布尔值,以便在 if 语句中检查真假

不正确。 JavaScript 是一种动态类型语言。一个非零长度的字符串(任何 URL 都可以)将是一个真值。

var foo = "";
var bar = "some value";

if (foo) { console.log(foo); } else { console.log("foo is false"); }
if (bar) { console.log(bar); } else { console.log("bar is false"); }

【讨论】:

  • 所以ìf var? 为真,当var 为非空字符串且if var 为真时,当var 为内容为“真”的字符串时,我是否正确?
  • 只是为了增加清晰度:这是由于 JavaScript developer.mozilla.org/en-US/docs/Glossary/Truthy 中的 Truthy 概念 - 当字符串被评估为布尔值时,它的长度为非零时为真,长度为假时为假0 长度。
  • 纠正自己:if var? 在 var 为非零长度字符串时为真,if var 在 var 为值为真的布尔值时为真。
  • 但问题是 CoffeeScript,所以 if(x)if(x?) 是非常不同的东西。
【解决方案2】:

了解 javascript 如何转换布尔值的一个很好的简单方法是使用双重否定 !!

不确定是否反对,但我个人觉得这种技术很有用,主要是因为我打开了 Chrome,如果我不确定布尔评估,我只需打开控制台并输入我正在检查的内容......例如。输入 !!-1 ,在这种情况下它会返回 true,其他一些语言可能会将其视为 false

例如。

console.log( "''", !!'' );  //false
console.log( "hello2", !!'hello' );  //true
console.log( "0", !!0 );  //false
console.log( "'0'", !!'0' );  //true
console.log( "1", !!1 ); //true
console.log( "true", !!true ); //true
console.log( "null", !!null ); //false
console.log( "undefined", !!undefined ); //false

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多