繁体   English   中英

在JavaScript函数中返回布尔值true或false

[英]Return boolean true or false in a JavaScript function

我无法让我的函数返回布尔值为false时提供的语句。

尝试将Boolean()添加到代码中,尝试使所有可能的结果看起来像

singleArg“ 0” || singleArg“某物”等

 function isTruthy(singleArg) { let isitTrue = ''; if (singleArg === 'somecontent' || 1 || [2, 3, 4], { name: 'Alex' }) { isitTrue = true; } else if (singleArg === false || null || undefined || 0 || "") { isitTrue === 'The boolean value false is falsey'; isitTrue === 'The null value is falsey'; isitTrue === 'undefined is falsey'; isitTrue === 'The number 0 is falsey'; isitTrue == 'The empty string is falsey (the only falsey string)'; } return isitTrue; } console.log(isTruthy(('somecontent'))); 

编写一个isTruthy函数,它接受任何类型的单个参数。

如果该参数为“真”,则isTruthy应该返回true。

如果值为“ falsey”,请注销以下与测试值类型相对应的消息之一。

您可以使用switch语句直接检查值。

在这种情况下,使用return语句 ,可以省略break语句 ,因为return终止函数的执行,因此会终止switch

 function isTruthy(value) { switch (value) { case false: return 'The boolean value false is falsy'; case null: return 'The null value is falsy'; case undefined: return 'undefined is falsy'; case 0: return 'The number 0 is falsy'; case '': return 'The empty string is falsy (the only falsy string)'; } return Boolean(value); } console.log(isTruthy(false)); console.log(isTruthy(null)); console.log(isTruthy(undefined)); console.log(isTruthy(0)); console.log(isTruthy('')); console.log(isTruthy(NaN)); // false console.log(isTruthy(true)); console.log(isTruthy({})); console.log(isTruthy(1e3)); console.log(isTruthy('yes!')); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

它总是会返回true,因为您在第一个if块中|| 1.总是评估为真。

如果希望将singleArg与值1进行比较,则需要编写singleArg === 'somecontent' || singleArg === 1 ... singleArg === 'somecontent' || singleArg === 1 ...

同样,对于您的第二个if块,所有这些值始终求值为false。 您实际上可以简单地写:

if (!singleArg)

无论值是false,null,undefined,0还是空字符串,它将始终返回false。

正如人们已经指出的那样,您可以简单地检查!Boolean(arg)

这是有关如何重写函数的建议:

function isTruthy(singleArg) {
  if ( !Boolean(singleArg) ) {
    switch( typeof singleArg ) {
      case "boolean":
        console.log( "The boolean value false is falsey" );
        break;

      case "object":  // typeof null is an object
        console.log( "The null value is falsey" );
        break;

      case "undefined":
        console.log( "undefined is falsey" );
        break;

      case "number":
        console.log( "The number 0 is falsey" );
        break;

      case "string":
        console.log( "The empty string is falsey (the only falsey string)" );
        break;

      default:
        console.log( "NaN?" );
        console.log( typeof singleArg );
        break;
    }
    return;
  }
  console.log( true );
}

isTruthy();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM