gpt4 book ai didi

javascript - 传统 bool 测试

转载 作者:行者123 更新时间:2023-11-28 11:10:39 27 4
gpt4 key购买 nike

问题

Although you can explicitly check if a value is true or false, it's a convention in JavaScript to test against all falsy values. For example, we can test if a variable value is falsy by testing if (value).

代码

function UnconventionalDefaults(params, defaultParams) {
if (params === undefined) {
params = defaultParams;
}

// function would do work here

return params;
}

// Modify this function to set params to defaultParams if params
// is falsy
function moreConventionalDefaults(params, defaultParams) {
// do a more conventional check here (check if params is falsy,
// and not just undefined
if(params === undefined){
params === defaultParams;
}else if(params === null){
params === defaultParams;
}else if(params === ""){
params === defaultParams;
}else if(params === false){
params === defaultParams;
}

return params;
}

尽管我正在测试所有虚假值,但此代码并未被接受。我做错了什么?有更好的方法吗?

最佳答案

  • 您不能使用 === 来分配参数。请改用 =

  • 此外,这些并不都是假值,您缺少 0NaN

整个方法可以简化为:

function moreConventionalDefaults(params, defaultParams) {
return params || defaultParams;
}

params 将被评估,如果它是假的,那么 defaultParams 将被返回。

编辑:阅读精彩文章 Exploring JavaScript’s Logical OR Operator作者:Addy Osmani 了解更多信息。

关于javascript - 传统 bool 测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8344795/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com