當前位置: 首頁>>編程語言>>正文


JavaScript調試利器console.log()

簡介

Almost all web browsers and JavaScript environments support writing messages to a console using a suite of logging methods. The most common of these is the `console.log()` method.


起步

Open up the JavaScript Console in your browser, type the following, and press Enter:

console.log("Hello, World!");

In the example above, the console.log() function prints Hello, World! to the console, along with a new line, and returns undefined (shown above in the console output window), because it has no explicit return value.

The console.log() function is predominantly used for debugging purposes.


輸出變量

console.log() can be used to log variables of any kind, not only strings. Just pass the variable that you want to be displayed in the console, for example:

var foo = "bar";  console.log(foo);

Will log in the console…

If you want to log two or more values, simply separate them with commas:

console.log("thisVar:", thisVar, "and that", thatVar);


輸出對象

Below depicts the result of logging an object, which can be useful, for example, to log JSON responses received from an API call:

console.log({'Email': '', 'Groups': {}, 'Id': 33, 'IsHiddenInUI': false, 'IsSiteAdmin': false, 'LoginName': 'i:0#.w|virtualdomain\user2', 'PrincipalType': 1, 'Title': 'user2'});

Will log in the console…


輸出函數

The console can also be used to show the return value of a function. In the example below, isNaN() will be executed and the value returned by this function will be shown in the console;

console.log also has the ability to display function definitions by passing a non invoked instance of the function.

var func = function(){console.log("hello from func");} console.log(func.toString());

Will log to the console…


輸出HTML元素

You have the ability to log any element which exists within the DOM. In this case we log the body element;

console.log(document.body);

Will log to the console…

本文由《純淨天空》出品。文章地址: https://vimsky.com/zh-tw/article/1737.html,未經允許,請勿轉載。