Usage of console in Javascript

Source: Internet
Author: User
Tags date end expression connect numeric value string first row touch
The console object is the native object of JavaScript, a bit like the standard output stdout and standard error stderr of UNIX systems, which can output a variety of information to debug a program, and also provides a number of additional methods for developers to invoke. There are two common uses for it.
    • Displays the error message when the Web page code runs.

    • Provides a command-line interface for interacting with Web page code.

Browser implementation

The browser implementation of the console object, contained within the development tools that the browser brings. Take the Chrome browser's developer tool (Developer tools) For example, first use one of the following three methods to open it.

  1. Press F12 or control+shift+i (PC platform)/Alt+command+i (Mac platform).

  2. Select Tools/Developer tools from the menu.

  3. On a page element, open the right-click menu and select the "Inspect element".

After you open the developer tools, you can see that there are eight panel cards at the top to choose from:

  • Elements: HTML source and CSS code for debugging Web pages.

  • Resources: View the various resource files that the Web page loads (such as code files, font files, CSS files, and so on), as well as various content created on your hard disk (such as local caching, cookies, locals storage, and so on).

  • Network: View HTTP communications for a Web page.

  • Sources: Debug JavaScript code.

  • Timeline: View changes in the behavior of various web pages over time.

  • Profiles: View the performance of a Web page, such as CPU and memory consumption.

  • Audits: Provides suggestions for web optimization.

  • Console: Used to run JavaScript commands.

These eight panels have their own purpose, and the following are for the console panel, also known as the console. The console panel is basically a command-line window, and you can type various commands at the prompt.

The various methods provided by the console object are described below.

Methods of the Console object

Log (), info (), debug ()

The Console.log method is used to output information in the console window. It can accept multiple parameters and connect their results to output.

Console.log ("Hello World")
//Hello World

console.log ("A", "B", "C")
//a B C

The Console.log method automatically adds line breaks at the end of each output.

Console.log (1);
Console.log (2);
Console.log (3);
1
//2
//3

If the first argument is a format string (using a format placeholder), the Console.log method replaces the placeholder in turn with the following arguments, and then outputs.

Console.log ("%s +%s =%s", 1, 1, 2)
//  1 + 1 = 2

In the code above, the first parameter of the Console.log method has three placeholders (%s), and the 第二、三、四个 parameter replaces the three placeholder in turn when it is displayed. The Console.log method supports placeholders with the following, and data in different formats must use a placeholder for the corresponding format.

    • %s string
    • %d integer
    • %i Integer
    • %f floating-point numbers
    • %o Links to Objects
    • %c CSS format string
var number = one * 9;
var color = ' Red ';

Console.log ('%d%s balloons ', number, color);
Red Balloons

In the code above, the second argument is a numeric value, the corresponding placeholder is%d, the third argument is a string, and the corresponding placeholder is%s.

When you use the%c placeholder, the corresponding argument must be a CSS statement that is used to render the output in a CSS context.

Console.log ('%cthis text is styled! ',
  ' color: #86CC00; background-color:blue; font-size:20px; padding:3px; '
)

When the above code is run, the output is displayed as a blue-bottomed green word.

The two parameter formats of the log method can be used in conjunction with each other.

Console.log ("%s +%s", 1, 1, "= 2")
//1 + 1  = 2

If the argument is an object, Console.log displays the value of the object.

Console.log ({foo: ' Bar '})
//Object {foo: ' Bar '}

console.log (date)
/function Date () {[native code]}

The code above outputs the value of the Date object, and the result is a constructor.

Console.info () and Console.debug () are aliases for the Console.log method, and are used exactly the same. The Console.info method will precede the output information with a blue icon.

All methods of the console object can be overwritten. Therefore, you can define the Console.log method according to your own needs.

["Log", "info", "Warn", "error"].foreach (function (method) {
    Console[method] = console[method].bind (
        console,
        new Date (). toisostring ()
    );

Console.log ("a mistake!") ");
2014-05-18T09:00.000Z's gone wrong!

The code above indicates that the current time can be added to the display result using the custom Console.log method.

Warn (), error ()

The Warn method and the error method are also output information, they differ from the log method in that the Warn method outputs information with a yellow triangle at the front, indicating a warning; The error method outputs information with a red fork at the front, indicating an error, and displaying a stack of errors. All other uses are the same.

Console.error ("Error:%s (%i)", "Server is not Responding",
//Error:server are not responding)

console . Warn (' warning! Too few nodes (%d) ', document.childNodes.length)
//warning! Too few nodes (1)

Essentially, the log method is written to standard output (stdout), and the Warn method and the error method are written to the standard error (STDERR).

Table ()

For some composite types of data, the Console.table method can be converted to a table display.

var languages = [
  {name: "JavaScript", FileExtension: ". js"},
  {name: "Typescript", FileExtension: ". ts"},
  {name: ' Coffeescript ', fileextension: '. Coffee '}
];

Console.table (languages);

The language of the code above is converted to a table shown below.

(Index) name fileextension
0 "JavaScript" ". js"
1 "Typescript" ". ts"
2 "Coffeescript" ". Coffee"

The condition that the composite data is shown to the table is that the primary key must be owned. For the above array, the primary key is the numeric key. For an object, the primary key is its outermost key.

var languages = {
    CSharp: {name: "C #", Paradigm: "object-oriented"},
    FSharp: {name: "F #", Paradigm: "Functional " }
};

Console.table (languages);

The language of the code above is converted to a table shown below.

(Index) name Paradigm
CSharp "C #" "Object-oriented"
FSharp "F #" "Functional"

Count ()

The Count method is used for counting, outputting how many times it was invoked.

function greet (user) {
  console.count ();
  Return "HI" + user;
}

Greet (' Bob ')
//  : 1
//"Hi Bob"

greet (' Alice ')
//  : 2
//"Hi Alice"

greet (' Bob ')
//  : 3
//"Hi Bob"

Each time the above code calls the greet function, the internal Console.count method outputs the number of executions.

The method can accept a string as a parameter, as a label, to classify the number of executions.

function greet (user) {
  console.count (user);
  Return "HI" + user;
}

Greet (' Bob ')
//Bob:1
//"Hi Bob"

greet (' Alice ')
//Alice:1
//"Hi Alice"

greet (' Bob ')
//Bob:2
//"Hi Bob"

The code above, depending on the parameters, shows Bob executed two times, and Alice executes it once.

Dir ()

The Dir method is used to examine an object (inspect) and display it in a format that is easy to read and print.

Console.log ({f1: ' foo ', F2: ' Bar '})
//Object {f1: "foo", F2: "Bar"}

Console.dir ({f1: ' foo ', F2: ' Bar '})
/ /Object
//   F1: "foo"
//   F2: "Bar"
//   __proto__: Object

The code above shows the output of the Dir method, which is more readable and informative than the log method.

This method is useful for outputting DOM objects because all of the properties of the DOM object are displayed.

Console.dir (Document.body)

ASSERT ()

The Assert method accepts two arguments, the first argument is an expression, and the second argument is a string. The second argument is output only if the first argument is false, otherwise there will be no result.

Instance
Console.assert (true = = False, "judgment condition is not established")
//Assertion failed: judgment condition not tenable

Here is another example that determines whether the number of child nodes is greater than or equal to 500.

Console.assert (List.childNodes.length < 500, "number of nodes greater than or equal to 500")

Time (), Timeend ()

These two methods are used for timing and can calculate the exact time that an operation takes.

Console.time ("Array initialize");

var array= new Array (1000000);
for (var i = array.length-1 i >= 0; i--) {
    Array[i] = new Object ();

Console.timeend ("Array initialize");

Array initialize:1914.481ms

The time method represents the start of the timer, and the Timeend method represents the timing end. Their arguments are the names of the timers. After the Timeend method is invoked, the console window displays the timer name: the time spent.

Timeline (), Timelineend (), TimeStamp ()

The Console.timeline and Console.timelineend methods are used to define a new timeline that can be viewed in the timeline panel. These two methods are supported only by the Chrome developer tool.

Console.timeline (' Google Search ');

Do some work

console.timelineend (' Google Search ');

The code above defines a timeline called "Google Search", in which all events in the timeline are time-consuming and can be viewed in the timeline panel.

The Console.timestamp method is used in the middle of the top two methods to add a timestamp to the timeline. The name of the timestamp is the parameter of the timestamp method.

Profile (), Profileend ()

The Console.profile method is used to create a new performance tester (profile) whose parameters are the name of the performance tester.

Console.profile (' P ')
//profile ' P ' started.

The Console.profileend method is used to end a running performance tester.

Console.profileend ()
//profile ' P ' finished.

Open the Developer tool for the browser, and in the profile panel, you can see the results of the performance debugger running.

Group (), GroupEnd (), groupcollapsed ()

The Console.group and Console.groupend methods are used to group the displayed information. It is only useful when outputting large amounts of information, and is divided into a set of information that can be folded/expanded with the mouse.

Console.group (' Group One ');
Console.group (' Group Two ');

Some code

console.groupend ();//Group Two end
Console.groupend ()//Group One end

The Console.groupcollapsed method is similar to the Console.group method, and the only difference is that the contents of the group are closed (collapsed) rather than expanded on the first display.

Console.groupcollapsed (' fetching Data ');

Console.log (' Request Sent ');
Console.error (' Error:server not Responding ');

Console.groupend ();

The above code displays only one line of "fetching Data", which expands to show the two lines included.

Trace (), Clear ()

The Console.trace method displays the calling path of the currently executing code on the stack.

Console.trace ()
//Console.trace ()
//   (anonymous function)
//   Injectedscript._ Evaluateon
//   injectedscript._evaluateandwrap
//   Injectedscript.evaluate

The Console.clear method clears all output from the current console and resets the cursor back to the first row.

Command-line APIs

In the console, in addition to using the console object, you can use some command-line methods that come with the console itself.

(1) $_

The $_ property returns the value of the previous expression.

2+2
//4
$_
//4

(2) $ $

The console holds the last 5 DOM elements selected in the elements panel, and the first is the penultimate one, representing the penultimate, and so on until $ $.

(3) $ (selector)

$ (selector) returns an array that includes all DOM elements that are matched by a particular CSS selector. The method is actually an alias for the Document.queryselectorall method.

var images = $ (' img ');
For (all in images) {
    console.log (IMAGES[EACH].SRC);
}

The above code prints the SRC attribute of all the IMG elements in the Web page.

(4) $$ (selector)

$$ (selector) returns a selected Dom object, equivalent to Document.queryselectorall.

(5) $x (path)

The $x (path) method returns an array that contains all the DOM elements that match a particular XPath expression.

$x ("//p[a]")

The above code returns all the P elements that contain a element.

(6) Inspect (object)

The inspect (object) method opens the related panel and selects the appropriate element: The DOM element is displayed in the Elements panel, and the JavaScript object is displayed in profiles.

(7) Geteventlisteners (object)

The Geteventlisteners (object) method returns an object whose members are various events (such as click or KeyDown) in which the callback function is enlisted, each of which corresponds to an array, and the member of the array is the callback function for the event.

(8) Keys (object), values (object)

The keys (object) method returns an array that contains all the key names for a particular object.

The values (object) method returns an array that contains all the key values for a particular object.

var o = {' P1 ': ' A ', ' P2 ': ' B '};

Keys (o)
//["P1", "P2"]
values (o)
//["A", "B"]

(9) Monitorevents (object[, events]), unmonitorevents (object[, events))

Monitorevents (object[, Events]) method listens for specific events that occur on a particular object. When this occurs, an event object is returned that contains information about the event. The Unmonitorevents method is used to stop listening.

Monitorevents (window, "resize");

monitorevents (window, ["Resize", "scroll"])

The code above represents a single event and a listener method for multiple events.

Monitorevents ($, "mouse");
Unmonitorevents ($, "MouseMove");

The code above indicates how to stop listening.

Monitorevents allows monitoring of events of the same large class. All events can be grouped into four broad categories.

    • Mouse: "MouseDown", "MouseUp", "click", "DblClick", "MouseMove", "MouseOver", "mouseout", "MouseWheel"
    • Key: "KeyDown", "KeyUp", "KeyPress", "TextInput"
    • Touch: "Touchstart", "Touchmove", "Touchend", "Touchcancel"
    • Control: "Resize", "scroll", "Zoom", "Focus", "blur", "select", "Change", "Submit", "Reset"
Monitorevents ($ ("#msg"), "key");

The code above indicates an event that listens for all key classes.

(a) profile ([name]), Profileend ()

The profile method is used to start a CPU performance test of a specific name, and the Profileend method is used to end the performance test.

Profile (' My Profile ')

profileend ("My Profile")

(11) Other methods

The command line API also provides the following methods.

    • The clear () method clears the history of the console.
    • The copy (object) method copies a specific DOM element to the Clipboard.
    • The Dir (object) method displays all the properties of a particular object and is an alias for the Console.dir method.
    • The Dirxml (object) method displays the XML form of a particular object and is an alias to the Console.dirxml method.

Debugger statement

The debugger statement must be used in conjunction with the debugging tool, and the debugger statement will not produce any results without a debugger.

In the Chrome browser, when the code runs to the row specified by debugger, it pauses and automatically opens the console interface. It works like setting breakpoints.

for (var i = 0;i<5;i++) {
    console.log (i);
    if (i===2) debugger;
}

When the above code prints out the 0,1,2, it pauses, automatically opens the console window and waits for further processing.

Mobile End Development

(This section is here for temporary storage)

Analog mobile phone viewport (viewport)

The Chrome Browser developer tool provides an option to simulate the display of your phone's screen.

Open the overrides panel for settings and select the appropriate user agent and device metrics options.

The User agent allows the current browser to emit a mobile browser's agent string, Device metrics makes the current browser's viewport into the phone's viewport size. These two options can be selected independently, not necessarily at the same time.

Simulate Touch events

We can simulate JavaScript touch events on the PC side.

First, open the Chrome Browser developer tool, select the overrides panel in the "Settings" tab and check the "Enable Touch events" option.

The mouse then triggers the Touchstart, Touchmove, and Touchend events. (At this point, the events of the mouse itself remain valid.) )

As for multi-touch, it is necessary to have equipment to support this function to simulate, you can refer to multi-touch web development.

Simulation of latitude and longitude

The Chrome browser's developer tool can also simulate the current latitude and longitude data. Open the overrides panel of settings, select the Override Geolocation option, and fill in the corresponding latitude and longitude data.

Remote removal error

(1) Chrome for Android

The Chrome browser on the Android device supports USB debugging. The PC side needs to install the Android SDK and Chrome browser, and then connect the phone with the PC with a USB cable to refer to the official documentation.

(2) Opera

Opera browser's debugging environment Dragonfly supports remote debugging (tutorial).

(3) Firefox for Android

Refer to the official documentation.

(4) Safari on iOS6

You can use the Safari 6 browser on your Mac desktop to make remote debugging (tutorials).

Google Closure

(This section is here for temporary storage)

Google closure is a JavaScript source processing tool provided by Google, designed to compress and merge multiple JavaScript script files.

Google closure is developed using the Java language and must be installed before using Java. Then, go to the official website to download, where we use the compiler (compiler).

First, look at the use Help.

Java-jar/path/to/closure/compiler.jar--help

You can complete the merge by following the script command immediately following the script you want to merge.

Java-jar/path/to/closure/compiler.jar *.js

Using the--js parameter, you can ensure that the file is merged in the order of the parameters.

Java-jar/path/to/closure/compiler.jar--js script1.js--js script2.js--js

However, such a run result is to output the merged file to the screen (standard output), so you need to use the--js_output_file parameter to specify the merged file name.

Java-jar/path/to/closure/compiler.jar--js script1.js--js script2.js--js script3.js--js_output_file Scripts-compiled.js

Javascript Performance Test

(This section is here for temporary storage)

First approach

The most common way to test performance is to repeat the same operation N times, and then calculate the average time for each operation.

var totaltime,
    start = new Date,
    iterations = 6;

while (iterations--) {
  //Code snippet goes here
}

//totaltime→the number of milliseconds it took to execut e
//The code Snippet 6 times
totaltime = new Date-start;

The problem with the above code is that because the computer's performance is increasing, if you repeat it only 6 times, you are likely to get 0 milliseconds, less than 1 milliseconds, and the JavaScript engine will not be able to measure it.

The second approach

Another idea is how many operations have been completed in the test unit time.

var Hz,
    period,
    starttime = new Date,
    runs = 0;

do {
  //Code snippet goes here
  runs++;
  TotalTime = new Date-starttime;
} while (TotalTime < 1000);

Convert ms to seconds
totaltime/= 1000;

Period→how long per operation
period = Totaltime/runs;

Hz→the number of operations per second
Hz = 1/period;

Can is shortened to
//Hz = (runs * 1000)/totaltime;

The attention of this approach is that the test structure is affected by the external environment, in order to get the correct structure, must repeat many times.

Original address: http://javascript.ruanyifeng.com/tool/console.html



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.