【问题标题】:JavaScript Evaluation Shorthand issueJavaScript 评估速记问题
【发布时间】:2020-06-25 13:07:25
【问题描述】:

可能非常简单,但我不确定如何正确编写以下评估和分配,我正在尝试将配置值分配给小部件并在未设置配置时设置回退默认值。如果我尝试的方式不可能,我可以在设置值之前回退到 if/else。感谢任何指点。

console.log(config);

    // Outputs
    {autoplay: false}

    $(el).slick({
        // Sets autoplay to true instead of false, as it evaluates it as not null (I think)
        autoplay: config.autoplay || true,
        // If i set it this way, it works with the correct value as not being evaluated, but then i have no fallback value
        //autoplay: config.autoplay
    });

【问题讨论】:

  • 如果config.autoplay ?? true 不是一个选项,请尝试(config.hasOwnProperty("autoplay") ? config.autoplay : true)
  • 这能回答你的问题吗? How to set default boolean values in JavaScript? — 在“js 默认布尔值”的第一批 Google 搜索结果中。

标签: javascript boolean


【解决方案1】:
$(el).slick({
  autoplay: config.autoplay != null ? config.autoplay : true
});

这将检查该值是否既不是null 也不是undefined

由于自动播放为假,false || true 将始终为真。

【讨论】:

    【解决方案2】:

    如果你只想要一个默认值,你也可以使用它。

    let config
    const defaults = {autoplay:true}
    
    config = {}
    console.log({...defaults,...config})
    
    config = {autoplay:true}
    console.log({...defaults,...config})
    
    config = {autoplay:false}
    console.log({...defaults,...config})
    
    //inlined
    config = {}
    console.log({autoplay:"default",...config})
    
    //multiple
    config = {arg2:"replaced",arg10:"extended"}
    console.log({arg1:1, arg2:2, arg3:3,...config})

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-10-25
      • 2013-07-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多