簡體   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