• Node.js Video Tutorials

NodeJS - console.assert() 方法



Node.js 的 console.assert() 方法會在斷言為假時將錯誤訊息列印到控制檯,如果斷言為真,則什麼也不會發生。

在此方法中,如果我們提供 假值 (falsy) 作為引數,它將停止程式執行並告訴我們我們做出的斷言是 錯誤的 (false)。如果我們提供 真值 (truthy) 作為引數,則不會返回或列印任何內容。

為了更好地理解,讓我們瞭解 Node.js 的 console.assert() 方法的語法和用法。

語法

以下是 Node.js console.assert() 方法 的語法:

console.assert(value[,…message]);

引數

此方法接受兩個引數,如下所述。

  • value − 如果給定值為 真值 (truthy),則測試此值。

  • message − 此引數中傳遞的任何 訊息引數 將被視為錯誤訊息。

返回值

如果我們做出的斷言為 真 (true),則此方法不返回任何內容。如果斷言失敗,則它將丟擲錯誤以及錯誤訊息到 stderr。

以下是 真值 (truthy)

  • true

  • {}

  • []

  • 30

  • "0"

  • "false"

  • -32

  • 12n

  • 3.14

  • -3.14

  • Infinity

  • -Infinity

示例

在下面的示例中,我們透過將 真值 (truthy) 傳遞給 value 引數,並將訊息傳遞給該方法的 message 引數來呼叫 Node.js console.assert() 方法。

const console = require('console');
console.assert(true, 'This asserttion is true');

輸出

從下圖的輸出中可以看到,我們傳遞的值是 真值 (truthy)。因此,此方法不會返回任何內容。

// Returns nothing

示例

在下面的示例中,我們透過傳遞不同型別的 真值 (truthy) 值以及訊息到該方法的 message 引數來呼叫 Node.js console.assert() 方法。

const console = require('console');
const emp = [];
const num = 30;
const inf = Infinity;
console.assert(emp, '"${emp}" is a truthy value');
console.assert(num, '"${num}" is a truthy value');
console.assert(inf, '"${inf}" is a truthy value')

輸出

如果我們編譯並執行上面的程式碼,我們將得到如下圖所示的輸出。我們傳入的值是 真值 (truthy)。因此,此方法不會返回任何內容。

// Returns nothing

以下是 假值 (falsy)

  • false

  • 0

  • -0

  • 0n

  • "", '', ``

  • null

  • undefined

  • NaN

示例

在下面的示例中,我們透過將 假值 (falsy) 傳遞給 value 引數,並將錯誤訊息傳遞給該方法的 message 引數來呼叫 console.assert() 方法。

const console = require('console');
console.assert(false, 'This is a falsy value');

輸出

從下面的輸出中可以看到,我們傳遞的值是 假值 (falsy)。因此,我們做出的斷言失敗,該方法返回“斷言失敗”的輸出以及其錯誤訊息。

Assertion failed: This is a falsy value

示例

在下面的示例中,我們透過傳遞不同型別的 假值 (falsy) 值以及錯誤訊息到該方法的 message 引數來呼叫 console.assert() 方法。

const console = require('console');
const zero = 0;
const negzero = -0;
const emp = "";
const NULL = null;
const und = undefined;
const nan = NaN;
console.assert(zero, '"${zero}" is a falsy value');
console.assert(negzero, '"${negzero}" is a falsy value');
console.assert(emp, '"${emp}" is a falsy value');
console.assert(NULL, '"${NULL}" is a falsy value');
console.assert(und, '"${und}" is a falsy value');
console.assert(nan, '"${nan}" is a falsy value');

輸出

從下面的輸出中可以看到,我們做出的斷言失敗,該方法返回“斷言失敗”的輸出以及其指定的錯誤訊息。

Assertion failed: "${zero}" is a falsy value
Assertion failed: "${negzero}" is a falsy value
Assertion failed: "${emp}" is a falsy value
Assertion failed: "${NULL}" is a falsy value
Assertion failed: "${und}" is a falsy value
Assertion failed: "${nan}" is a falsy value
nodejs_console_module.htm
廣告
© . All rights reserved.