短路评估并将 true 或 false 分配给变量
Short circuit evaluation and assigning either true or false to a variable
我有以下预配置
const preloadedConfig = {
"configA": null, // either true, false or null is allowed
};
然后我在页面加载时进行了以下初始化
let finalConfig = preloadedConfig.configA || true;
场景:
预加载配置中的属性可以更改为 true、false 或 null 根据用户喜好
我希望使用短路评估来确定用户对页面加载的选择。如果用户没有提供 choice(null),则默认选择为 true
我的问题:
基于从here中提取的以下内容:
Falsy values are those who coerce to false when used in boolean context, and they are 0, null, undefined, an empty string, NaN and of course false.
评价如下:
true >> evaluted true // ok
null >> evaluted true // ok
false >> evaluted true // the problem area
如果用户提供 false 的配置选项,最终评估的值将始终为真,因为它是一个“假值”。
我的期望结果是一个布尔值false如果提供的值是false。
在使用短路评估并允许 3 种类型的输入值 null、true 或 false 时,我应该怎么做才能使这项工作正常进行?
在现代环境中(或使用转译器),我会使用 nullish 合并运算符,仅当左侧为 null 或未定义时才采用右侧:
let finalConfig = preloadedConfig.configA ?? true;
否则,使用条件运算符:
let finalConfig = preloadedConfig.configA == null ? true : preloadedConfig.configA;
您可以改用 nullish coalescing operator。
let finalConfig = preloadedConfig.configA ?? true;
或者,您可以使用 hasOwnProperty
检查。
let finalConfig = preloadedConfig.hasOwnProperty('configA') ? preloadedConfig.configA : true;
您可以使用旧的 Object.assign 或现代的 destruct ... prop.
使默认规则更好一些
这将覆盖 configA,即使是 null
const yourConfig = {
configA: true,
...preloadedConfig
}
旧环境会
Obejct.assign({configA: true},preloadedConfig)
编辑:
默认为空值是
const yourConfig = {
configA: true,
...Object.fromEntries(Object.entries(preloadedConfig).filter(([key,val])=>val!==null))
}
我有以下预配置
const preloadedConfig = {
"configA": null, // either true, false or null is allowed
};
然后我在页面加载时进行了以下初始化
let finalConfig = preloadedConfig.configA || true;
场景:
预加载配置中的属性可以更改为 true、false 或 null 根据用户喜好
我希望使用短路评估来确定用户对页面加载的选择。如果用户没有提供 choice(null),则默认选择为 true
我的问题:
基于从here中提取的以下内容:
Falsy values are those who coerce to false when used in boolean context, and they are 0, null, undefined, an empty string, NaN and of course false.
评价如下:
true >> evaluted true // ok
null >> evaluted true // ok
false >> evaluted true // the problem area
如果用户提供 false 的配置选项,最终评估的值将始终为真,因为它是一个“假值”。
我的期望结果是一个布尔值false如果提供的值是false。
在使用短路评估并允许 3 种类型的输入值 null、true 或 false 时,我应该怎么做才能使这项工作正常进行?
在现代环境中(或使用转译器),我会使用 nullish 合并运算符,仅当左侧为 null 或未定义时才采用右侧:
let finalConfig = preloadedConfig.configA ?? true;
否则,使用条件运算符:
let finalConfig = preloadedConfig.configA == null ? true : preloadedConfig.configA;
您可以改用 nullish coalescing operator。
let finalConfig = preloadedConfig.configA ?? true;
或者,您可以使用 hasOwnProperty
检查。
let finalConfig = preloadedConfig.hasOwnProperty('configA') ? preloadedConfig.configA : true;
您可以使用旧的 Object.assign 或现代的 destruct ... prop.
使默认规则更好一些这将覆盖 configA,即使是 null
const yourConfig = {
configA: true,
...preloadedConfig
}
旧环境会
Obejct.assign({configA: true},preloadedConfig)
编辑:
默认为空值是
const yourConfig = {
configA: true,
...Object.fromEntries(Object.entries(preloadedConfig).filter(([key,val])=>val!==null))
}