From 218934fa2ed1c702a6d3923d2aa2cc6b43c48684 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:43:23 -0500 Subject: initial commit --- files/zh-tw/web/api/console/assert/index.html | 118 +++++++++++ files/zh-tw/web/api/console/index.html | 289 ++++++++++++++++++++++++++ 2 files changed, 407 insertions(+) create mode 100644 files/zh-tw/web/api/console/assert/index.html create mode 100644 files/zh-tw/web/api/console/index.html (limited to 'files/zh-tw/web/api/console') diff --git a/files/zh-tw/web/api/console/assert/index.html b/files/zh-tw/web/api/console/assert/index.html new file mode 100644 index 0000000000..415b4cfa9a --- /dev/null +++ b/files/zh-tw/web/api/console/assert/index.html @@ -0,0 +1,118 @@ +--- +title: Console.assert() +slug: Web/API/console/assert +tags: + - API + - DOM + - Debugging + - 函式 + - 控制台 + - 網頁控制台 + - 網頁開發 +translation_of: Web/API/console/assert +--- +
{{APIRef("Console API")}}
+ +

如果斷言(assertion)為非(false),主控台會顯示錯誤訊息;如果斷言為是(true),則不發生任何事。

+ +

{{AvailableInWorkers}}

+ +
+

注意在 Node.js 內 console.assert() 方法的實做,與瀏覽器並不相同。

+ +

瀏覽器內呼叫 falsy 的 console.assert() 斷言出現 message,但不會中斷程式碼的執行。然而在 Node.js 裡面,falsy 斷言會拋出 AssertionError 錯誤。

+
+ +

語法

+ +
console.assert(assertion, obj1 [, obj2, ..., objN]);
+console.assert(assertion, msg [, subst1, ..., substN]); // c-like message formatting
+
+ +

參數

+ +
+
assertion
+
布林表達式。如果斷言為非,訊息會出現在主控台上。
+
obj1 ... objN
+
要印出來的 JavaScript 物件名單。 The string representations of each of these objects are appended together in the order listed and output.
+
msg
+
包含零個以上的 JavaScript 替代(substitution)字串。
+
subst1 ... substN
+
JavaScript objects with which to replace substitution strings within msg. This parameter gives you additional control over the format of the output.
+
+ +

請參見 {{domxref("console")}} 的 Outputting text to the console 以獲取詳細資訊。

+ +

範例

+ +

以下程式碼示範一個 JavaScript 物件的斷言使用:

+ +
const errorMsg = 'the # is not even';
+for (let number = 2; number <= 5; number += 1) {
+    console.log('the # is ' + number);
+    console.assert(number % 2 === 0, {number: number, errorMsg: errorMsg});
+    // or, using ES2015 object property shorthand:
+    // console.assert(number % 2 === 0, {number, errorMsg});
+}
+// output:
+// the # is 2
+// the # is 3
+// Assertion failed: {number: 3, errorMsg: "the # is not even"}
+// the # is 4
+// the # is 5
+// Assertion failed: {number: 5, errorMsg: "the # is not even"}
+
+ +

請注意,雖然包含替換字符串的字符串在 Node 中用作 console.log 的參數,但很多(如果不是大多數)瀏覽器...

+ +
console.log('the word is %s', 'foo');
+// output: the word is foo
+
+ +

...在所有瀏覽器中,使用此類字符串目前無法作為console.assert的參數使用:

+ +
console.assert(false, 'the word is %s', 'foo');
+// correct output in Node (e.g. v8.10.0) and some browsers
+//     (e.g. Firefox v60.0.2):
+// Assertion failed: the word is foo
+// incorrect output in some browsers
+//     (e.g. Chrome v67.0.3396.87):
+// Assertion failed: the word is %s foo
+
+ +

有關詳細信息,請參閱 {{domxref("console")}} 文檔中的將文本輸出到控制台

+ +

規範

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("Console API", "#assert", "console.assert()")}}{{Spec2("Console API")}}初始定義
+ +

瀏覽器相容性

+ + + +

{{Compat("api.Console.assert")}}

+ +

參見

+ + diff --git a/files/zh-tw/web/api/console/index.html b/files/zh-tw/web/api/console/index.html new file mode 100644 index 0000000000..36320a69a8 --- /dev/null +++ b/files/zh-tw/web/api/console/index.html @@ -0,0 +1,289 @@ +--- +title: Console +slug: Web/API/Console +tags: + - API + - Debugging + - Interface + - NeedsCompatTable + - NeedsTranslation + - Reference + - TopicStub + - console + - web console +translation_of: Web/API/Console +--- +
{{APIRef("Console API")}}
+ +

The Console object provides access to the browser's debugging console (e.g. the Web Console in Firefox). The specifics of how it works varies from browser to browser, but there is a de facto set of features that are typically provided.

+ +

The Console object can be accessed from any global object. {{domxref("Window")}} on browsing scopes and {{domxref("WorkerGlobalScope")}} as specific variants in workers via the property console. It's exposed as {{domxref("Window.console")}}, and can be referenced as simply console. For example:

+ +
console.log("Failed to open the specified link")
+ +

This page documents the {{anch("Methods")}} available on the Console object and gives a few {{anch("Usage")}} examples.

+ +

{{AvailableInWorkers}}

+ +

Methods

+ +
+
{{domxref("Console.assert()")}}
+
Log a message and stack trace to console if the first argument is false.
+
{{domxref("Console.clear()")}}
+
Clear the console.
+
{{domxref("Console.count()")}}
+
Log the number of times this line has been called with the given label.
+
{{domxref("Console.debug()")}}
+
An alias for log(). +
Note: Starting with Chromium 58 this method only appears in Chromium browser consoles when level "Verbose" is selected.
+
+
{{domxref("Console.dir()")}} {{Non-standard_inline}}
+
Displays an interactive listing of the properties of a specified JavaScript object. This listing lets you use disclosure triangles to examine the contents of child objects.
+
{{domxref("Console.dirxml()")}} {{Non-standard_inline}}
+
+

Displays an XML/HTML Element representation of the specified object if possible or the JavaScript Object view if it is not possible.

+
+
{{domxref("Console.error()")}}
+
Outputs an error message. You may use string substitution and additional arguments with this method.
+
{{domxref("Console.exception()")}} {{Non-standard_inline}} {{deprecated_inline}}
+
An alias for error().
+
{{domxref("Console.group()")}}
+
Creates a new inline group, indenting all following output by another level. To move back out a level, call groupEnd().
+
{{domxref("Console.groupCollapsed()")}}
+
Creates a new inline group, indenting all following output by another level. However, unlike group() this starts with the inline group collapsed requiring the use of a disclosure button to expand it. To move back out a level, call groupEnd().
+
{{domxref("Console.groupEnd()")}}
+
Exits the current inline group.
+
{{domxref("Console.info()")}}
+
Informative logging of information. You may use string substitution and additional arguments with this method.
+
{{domxref("Console.log()")}}
+
For general output of logging information. You may use string substitution and additional arguments with this method.
+
{{domxref("Console.profile()")}} {{Non-standard_inline}}
+
Starts the browser's built-in profiler (for example, the Firefox performance tool). You can specify an optional name for the profile.
+
{{domxref("Console.profileEnd()")}} {{Non-standard_inline}}
+
Stops the profiler. You can see the resulting profile in the browser's performance tool (for example, the Firefox performance tool).
+
{{domxref("Console.table()")}}
+
Displays tabular data as a table.
+
{{domxref("Console.time()")}}
+
Starts a timer with a name specified as an input parameter. Up to 10,000 simultaneous timers can run on a given page.
+
{{domxref("Console.timeEnd()")}}
+
Stops the specified timer and logs the elapsed time in seconds since it started.
+
{{domxref("Console.timeStamp()")}} {{Non-standard_inline}}
+
Adds a marker to the browser's Timeline or Waterfall tool.
+
{{domxref("Console.trace()")}}
+
Outputs a stack trace.
+
{{domxref("Console.warn()")}}
+
Outputs a warning message. You may use string substitution and additional arguments with this method.
+
+ +

Usage

+ +

Outputting text to the console

+ +

The most frequently-used feature of the console is logging of text and other data. There are four categories of output you can generate, using the {{domxref("console.log()")}}, {{domxref("console.info()")}}, {{domxref("console.warn()")}}, and {{domxref("console.error()")}} methods respectively. Each of these results in output styled differently in the log, and you can use the filtering controls provided by your browser to only view the kinds of output that interest you.

+ +

There are two ways to use each of the output methods; you can simply pass in a list of objects whose string representations get concatenated into one string, then output to the console, or you can pass in a string containing zero or more substitution strings followed by a list of objects to replace them.

+ +

Outputting a single object

+ +

The simplest way to use the logging methods is to output a single object:

+ +
var someObject = { str: "Some text", id: 5 };
+console.log(someObject);
+
+ +

The output looks something like this:

+ +
[09:27:13.475] ({str:"Some text", id:5})
+ +

Outputting multiple objects

+ +

You can also output multiple objects by simply listing them when calling the logging method, like this:

+ +
var car = "Dodge Charger";
+var someObject = { str: "Some text", id: 5 };
+console.info("My first car was a", car, ". The object is:", someObject);
+ +

This output will look like this:

+ +
[09:28:22.711] My first car was a Dodge Charger . The object is: ({str:"Some text", id:5})
+
+ +

Using string substitutions

+ +

Gecko 9.0 {{geckoRelease("9.0")}} introduced support for string substitutions. When passing a string to one of the console object's methods that accepts a string, you may use these substitution strings:

+ + + + + + + + + + + + + + + + + + + + + + + + +
Substitution stringDescription
%o or %OOutputs a JavaScript object. Clicking the object name opens more information about it in the inspector.
%d or %iOutputs an integer. Number formatting is supported, for example  console.log("Foo %.2d", 1.1) will output the number as two significant figures with a leading 0: Foo 01
%sOutputs a string.
%fOutputs a floating-point value. Formatting is supported, for example  console.log("Foo %.2f", 1.1) will output the number to 2 decimal places: Foo 1.10
+ +
+

Note: Precision formatting doesn't work in Chrome

+
+ +

Each of these pulls the next argument after the format string off the parameter list. For example:

+ +
for (var i=0; i<5; i++) {
+  console.log("Hello, %s. You've called me %d times.", "Bob", i+1);
+}
+
+ +

The output looks like this:

+ +
[13:14:13.481] Hello, Bob. You've called me 1 times.
+[13:14:13.483] Hello, Bob. You've called me 2 times.
+[13:14:13.485] Hello, Bob. You've called me 3 times.
+[13:14:13.487] Hello, Bob. You've called me 4 times.
+[13:14:13.488] Hello, Bob. You've called me 5 times.
+
+ +

Styling console output

+ +

You can use the %c directive to apply a CSS style to console output:

+ +
console.log("This is %cMy stylish message", "color: yellow; font-style: italic; background-color: blue;padding: 2px");
+ +
The text before the directive will not be affected, but the text after the directive will be styled using the CSS declarations in the parameter.
+ +
 
+ +
+ +
 
+ +
+

Note: Quite a few CSS properties are supported by this styling; you should experiment and see which ones prove useful.

+
+ +
 
+ +
{{h3_gecko_minversion("Using groups in the console", "9.0")}}
+ +

You can use nested groups to help organize your output by visually combining related material. To create a new nested block, call console.group(). The console.groupCollapsed() method is similar but creates the new block collapsed, requiring the use of a disclosure button to open it for reading.

+ +
Note: Collapsed groups are not supported yet in Gecko; the groupCollapsed() method is the same as group() at this time.
+ +

To exit the current group, simply call console.groupEnd(). For example, given this code:

+ +
console.log("This is the outer level");
+console.group();
+console.log("Level 2");
+console.group();
+console.log("Level 3");
+console.warn("More of level 3");
+console.groupEnd();
+console.log("Back to level 2");
+console.groupEnd();
+console.debug("Back to the outer level");
+
+ +

The output looks like this:

+ +

nesting.png

+ +
{{h3_gecko_minversion("Timers", "10.0")}}
+ +

In order to calculate the duration of a specific operation, Gecko 10 introduced the support of timers in the console object. To start a timer, call the console.time() method, giving it a name as the only parameter. To stop the timer, and to get the elapsed time in milliseconds, just call the console.timeEnd() method, again passing the timer's name as the parameter. Up to 10,000 timers can run simultaneously on a given page.

+ +

For example, given this code:

+ +
console.time("answer time");
+alert("Click to continue");
+console.timeEnd("answer time");
+
+ +

Will log the time needed by the user to discard the alert box:

+ +

timerresult.png

+ +

Notice that the timer's name is displayed both when the timer is started and when it's stopped.

+ +
Note: It's important to note that if you're using this to log the timing for network traffic, the timer will report the total time for the transaction, while the time listed in the network panel is just the amount of time required for the header. If you have response body logging enabled, the time listed for the response header and body combined should match what you see in the console output.
+ +

Stack traces

+ +

The console object also supports outputting a stack trace; this will show you the call path taken to reach the point at which you call {{domxref("console.trace()")}}. Given code like this:

+ +
function foo() {
+  function bar() {
+    console.trace();
+  }
+  bar();
+}
+
+foo();
+
+ +

The output in the console looks something like this:

+ +

+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Console API')}}{{Spec2('Console API')}}Initial definition.
+ +

Browser compatibility

+ + + +

{{Compat("api.Console")}}

+ +

Notes

+ + + +

See also

+ + + +

Other implementations

+ + -- cgit v1.2.3-54-g00ecf