首页 > 解决方案 > JavaScript 评估速记问题

问题描述

可能非常简单,但我不确定如何正确编写以下评估和分配,我正在尝试将配置值分配给小部件并在未设置配置时设置回退默认值。如果我尝试的方式不可能,我可以在设置值之前回退到 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
    });

标签: javascriptboolean

解决方案


$(el).slick({
  autoplay: config.autoplay != null ? config.autoplay : true
});

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

由于自动播放是假的,false || true总是会导致真。


推荐阅读