• Node.js Video Tutorials

NodeJS - console.group() 方法



Node.js 的console.group()方法會將方法中給定的資訊以分組的形式返回。它通常用於根據一個或多個指定的列對查詢結果進行分組。您可以使用此方法聚合資料並在組上執行計算,例如總計、平均值和計數等。它還可以用於按升序或降序對分組記錄的輸出進行排序。

一個組包含一個合適的標題,標題下面會有一些合適的資訊或訊息。因此,我們在console.group()方法中傳遞的訊息將作為組標題。在組內,我們可以使用Node.js的console.log()函式編寫訊息。

語法

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

console.group([label)];]);

引數

  • label − 這是組的標籤。這將充當我們在控制檯上分組的組的標題。這不是必需引數;我們也可以不帶引數(標籤)使用此方法。

返回值

如果傳遞了label,此方法將在控制檯上將內容與label一起分組。否則,它將不帶標籤進行分組。

示例

Node.js 的console.group()方法只接受一個label引數(可選引數)。

注意 − 預設情況下,組將在控制檯中展開。

在這個例子中:

  • 我們使用console.group()建立一個組並傳遞一個引數(label)。此標籤將作為組標題。

  • 然後我們使用console.log()函式在組內編寫一些訊息。

  • 然後我們使用 Node.js 的console.groupEnd()方法結束組。

console.group("GROUP 1");
console.log("Knock knock....first message in Group 1");
console.log("Knock knock....second message in Group 1")
console.log("Done with the messages, closing the group now");
console.groupEnd();

輸出

正如我們在下圖的輸出中看到的,我們建立了一個帶有傳遞給console.group()方法的標籤的組,編寫了一些訊息,並關閉了該組。

GROUP 1
Knock knock....first message in Group 1
Knock knock....second message in Group 1
Done with the messages, closing the group now

為了更好地理解,請在瀏覽器的控制檯中執行上述程式碼。以下是上述程式在瀏覽器控制檯中的輸出。

group1.jpg

示例

在這個例子中,我們透過在一個組內呼叫一個組來建立巢狀組,然後我們相應地關閉這些組。

console.group("GROUP 1");
console.log("Knock knock....first message in Group 1");
console.log("Knock knock....second message in Group 1")
console.log("Done with the messages, closing the group now");
     
console.group("Nested group 1");
console.log("Knock knock....first message in Nested group 1");
console.log("Knock knock....second message in Nested group 1")
console.log("Now we are entering into another group inside nested group");
   
console.group("inner nested group");
console.log("OOPS! no messages here.");
console.groupEnd();
console.log("inner nested group ended");
console.groupEnd();
console.log("Nested group ended");
console.groupEnd();
console.log("GROUP 1 ended");

輸出

正如我們在下面的輸出中看到的,我們建立了主組,然後是子組,以及子組內的組。

GROUP 1
Knock knock....first message in Group 1
Knock knock....second message in Group 1
   Done with the messages, closing the group now
Nested group 1
   Knock knock....first message in Nested group 1
Knock knock....second message in Nested group 1
Now we are entering into another group inside nested group
   inner nested group
      OOPS! no messages here.
inner nested group ended
   Nested group ended
GROUP 1 ended

為了更好地理解,請在瀏覽器的控制檯中執行上述程式碼。以下是我們在瀏覽器控制檯中執行時的輸出。

nested_group
nodejs_console_module.htm
廣告
© . All rights reserved.