JavaScript 评价Shorthand 问题
JavaScript Evaluation Shorthand issue
可能非常简单,但我不确定如何正确编写以下评估和分配,我在其中尝试将配置值分配给小部件,并在未设置配置时设置回退默认值。如果我尝试的方式不可行,我可以在设置值之前回退到 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
});
$(el).slick({
autoplay: config.autoplay != null ? config.autoplay : true
});
这将检查值是否既不是 null
也不是 undefined
。
由于自动播放为 false,false || true
将始终为 true。
如果您只想要一个默认值,也可以使用它。
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})
可能非常简单,但我不确定如何正确编写以下评估和分配,我在其中尝试将配置值分配给小部件,并在未设置配置时设置回退默认值。如果我尝试的方式不可行,我可以在设置值之前回退到 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
});
$(el).slick({
autoplay: config.autoplay != null ? config.autoplay : true
});
这将检查值是否既不是 null
也不是 undefined
。
由于自动播放为 false,false || true
将始终为 true。
如果您只想要一个默认值,也可以使用它。
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})