JavaScript Console commands

JavaScript Console commands


You can use commands to send messages and perform other tasks in the JavaScript Console window of Visual Studio. For examples that show how to use that window, see  QuickStart: Debug JavaScript using the console . The information in this topic applies to Windows Store apps, Windows Phone Store apps, and apps created using Visual Studio Tools for Apache Cordova. For info on supported console commands in Cordova apps, see  Debug Your App Built with Visual Studio Tools for Apache Cordova . For info on using the console in Internet Explorer F12 tools, see  this topic .

If the JavaScript Console window is closed, you can open it while you're debugging in Visual Studio by choosing Debug > Windows > JavaScript Console.

System_CAPS_noteNote

If the window is not available during a debugging session, make sure that the debugger type is set to Script in the Debug properties for the project.

console object commands

This table shows the syntax for the console object commands that you can use in the JavaScript Console window, or that you can use to send messages to the console from your code. This object provides a number of forms so that you can distinguish between informational messages and error messages, if you want to.

You can use the longer command form window.console.[command] if you need to avoid possible confusion with local objects named console.

System_CAPS_tipTip

Older versions of Visual Studio do not support the complete set of commands. Use IntelliSense on the console object to get quick information about supported commands.

Command

Description

Example

assert(expression,message)

Sends a message if expression evaluates to false.

console.assert((x == 1), "assert message: x != 1");

clear()

Clears messages from the console window, including script-error messages, and also clears script that appears in the console window. Does not clear script that you entered into the console input prompt.

console.clear();

count(title)

Sends the number of times that the count command was called to the console window. Each call to count is uniquely identified by the optional title.

The existing entry in the console window is identified by the title parameter (if present) and updated by the count command. A new entry is not created.

console.count();

console.count("inner loop");

debug(message)

Sends message to the console window.

This command is identical to console.log.

Objects that are passed by using the command are converted to a string value.

console.debug("logging message");

dir(object)

Sends the specified object to the console window and displays it in an object visualizer. You can use the visualizer to inspect properties in the console window.

console.dir(obj);

dirxml(object)

Sends the specified XML node object to the console window and displays it as an XML node tree.

console.dirxaml(xmlNode);

error(message)

Sends message to the console window. The message text is red and prefaced by an error symbol.

Objects that are passed by using the command are converted to a string value.

console.error("error message");

group(title)

Starts a grouping for messages that are sent to the console window, and sends the optional title as a group label. Groups can be nested and appear in a tree view in the console window.

The group* commands can make it easier to view console window output in some scenarios, such as when a component model is in use.

console.group("Level 2 Header");
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");

groupCollapsed(title)

Starts a grouping for messages that are sent to the console window, and sends the optional title as a group label. Groups that are sent by using groupCollapsed appear in a collapsed view by default. Groups can be nested and appear in a tree view in the console window.

Usage is the same as thegroup command.

See the example for thegroup command.

groupEnd()

Ends the current group.

Requirements:

Visual Studio 2013

See the example for thegroup command.

info(message)

Sends message to the console window. The message is prefaced by an information symbol.

console.info("info message");

For more examples, seeFormatting console.log output later in this topic.

log(message)

Sends message to the console window.

If you pass an object, this command sends that object to the console window and displays it in an object visualizer. You can use the visualizer to inspect properties in the console window.

console.log("logging message");

msIsIndependentlyComposed(element)

Used in web apps. Not supported in Store apps using JavaScript.

Not supported.

profile(reportName)

Used in web apps. Not supported in Store apps using JavaScript.

Not supported.

profileEnd()

Used in web apps. Not supported in Store apps using JavaScript.

Not supported.

select(element)

Selects the specified HTML element in the DOM Explorer.

console.select(element);

time (name)

Starts a timer that's identified by the optional name parameter. When used with console.timeEnd, calculates the time that elapses between time and timeEnd, and sends the result (measured in ms) to the console using the name string as a prefix. Used to enable instrumentation of app code for measuring performance.

console.time("app start"); app.start(); console.timeEnd("app start");

timeEnd(name)

Stops a timer that's identified by the optional name parameter. See the time console command.

console.time("app start"); app.start(); console.timeEnd("app start");

trace()

Sends a stack trace to the console window. The trace includes the complete call stack, and includes info such as filename, line number, and column number.

console.trace(); 

warn(message)

Sends message to the console window, prefaced by a warning symbol.

Objects that are passed by using the command are converted to a string value.

console.warn("warning message");

Miscellaneous commands

These commands are also available in the JavaScript Console window (they are not available from code).

Command

Description

Example

$0$1$2$3,$4

Returns the specified element to the console window. $0 returns the element currently selected in DOM Explorer, $1 returns the element previously selected in DOM Explorer, and so on, up to the fourth previously selected element.

$3

$(id)

Returns an element by ID. This is a shortcut command for document.getElementById(id), where idis a string that represents the element ID.

$("contenthost")

$$(selector)

Returns an array of elements that match the specified selector using CSS selector syntax. This is a shortcut command for document.querySelectorAll().

$$(".itemlist")

cd()

cd(window)

Enables you to change the context for expression evaluation from the default top-level window of the page to the window of the specified frame. Calling cd() without parameters returns the context to the top-level window.

cd();

cd(myframe);

select(element)

Selects the specified element in DOM Explorer.

select(document.getElementById("element"));

select($("element"));

select($1);

dir(object)

Returns a visualizer for the specified object. You can use the visualizer to inspect properties in the console window.

dir(obj);

Checking whether a console command exists

You can check whether a specific command exists before attempting to use it. This example checks for the existence of the console.log command. If console.log exists, the code calls it.

JavaScript
if (console && console.log) {
    console.log("msg");
}

Examining objects in the JavaScript Console window

You can interact with any object that's in scope when you use the JavaScript Console window. To inspect an out-of-scope object in the console window, use console.log console.dir, or other commands from your code. Alternatively, you can interact with the object from the console window while it is in scope by setting a breakpoint in your code (Breakpoint > Insert Breakpoint).

Formatting console.log output

If you pass multiple arguments to console.log, the console will treat the arguments as an array and concatenate the output.

JavaScript
var user = new Object();
user.first = "Fred";
user.last = "Smith";

console.log(user.first, user.last);
// Output:
// Fred Smith

console.log also supports "printf" substitution patterns to format output. If you use substitution patterns in the first argument, additional arguments will be used to replace the specified patterns in the order they are used.

The following substitution patterns are supported:

  • %s - string
    %i - integer
    %d - integer
    %f - float
    %o - object
    %b - binary
    %x - hexadecimal
    %e - exponent

Here are some examples of using substitution patterns in console.log:

JavaScript
var user = new Object();
user.first = "Fred";
user.last = "Smith";
user.age = 10.01;
console.log("Hi, %s %s!", user.first, user.last);
console.log("%s is %i years old!", user.first, user.age);
console.log("%s is %f years old!", user.first, user.age);

// Output:
// Hi, Fred Smith!
// Fred is 10 years old!
// Fred is 10.01 years old!

See Also

QuickStart: Debug JavaScript using the console
Quickstart: Debug HTML and CSS

原文来自 https://msdn.microsoft.com/en-us/library/hh696634.aspx


-----------------------------------------------------------------------------------------------------------------------------------------------


The Console object provides access to the browser's debugging console (e.g., the Web Console in Firefox). The specifics of how it works vary 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, Window on browsing scopes, WorkerGlobalScope, and its specific variants in workers via property console. It's exposed as Window.console, and can be referenced as simply console. For example:

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

This page documents the Methods available on the Console object and gives a few Usage examples.

Note: This feature is available in  Web Workers.

MethodsEDIT

Console.assert()
Log a message and stack trace to console if first argument is  false.
Console.clear()
Clear the console.
Console.count()
Log the number of times this line has been called with the given label.
Console.debug()
An alias for  log()
Console.dir() 
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.
Console.dirxml() 

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

Console.error()
Outputs an error message. You may use  string substitution and additional arguments with this method.
Console.exception()   
An alias for  error()
Console.group()
Creates a new inline  group, indenting all following output by another level. To move back out a level, call  groupEnd().
Console.groupCollapsed()
Creates a new inline  group, indenting all following output by another level; 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().
Console.groupEnd()
Exits the current inline  group.
Console.info()
Informative logging information. You may use  string substitution and additional arguments with this method.
Console.log()
For general output of logging information. You may use  string substitution and additional arguments with this method.
Console.profile() 
Starts the browser's build-in profiler (for example, the  Firefox performance tool). You can specify an optional name for the profile.
Console.profileEnd() 
Stops the profiler. You can see the resulting profile in the browser's performance tool (for example, the  Firefox performance tool).
Console.table()
Displays tabular data as a table.
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.
Console.timeEnd()
Stops the specified  timer and logs the elapsed time in seconds since its start.
Console.timeStamp() 
Adds a marker to the browser's  Timeline or  Waterfall tool.
Console.trace()
Outputs a  stack trace.
Console.warn()
Outputs a warning message. You may use  string substitution and additional arguments with this method.

UsageEDIT

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 console.log()console.info()console.warn(), and console.error() methods. Each of these results in output that's 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 the objects with which 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 (Firefox 9.0 / Thunderbird 9.0 / SeaMonkey 2.6) 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 string Description
%o or %O Outputs a JavaScript object. Clicking the object name opens more information about it in the inspector.
%d or %i Outputs 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
%s Outputs a string.
%f Outputs 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

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 provide useful.

 

Using groups in the console

Requires Gecko 9.0(Firefox 9.0 / Thunderbird 9.0 / SeaMonkey 2.6)

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:

JavaScript Console commands_第1张图片

Timers

Requires Gecko 10.0(Firefox 10.0 / Thunderbird 10.0 / SeaMonkey 2.7)

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 console.trace(). Given code like this:

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

foo();

The output in the console looks something like this:

JavaScript Console commands_第2张图片

SpecificationsEDIT

Specification Status Comment
Console API Living Standard Initial definition.

NotesEDIT

  • At least in Firefox, if a page defines a console object, that object overrides the one built into Firefox.
  • Prior to Gecko 12.0, the console object's methods only work when the Web Console is open. Starting with Gecko 12.0, output is cached until the Web Console is opened, then displayed at that time.
  • It's worth noting that the Firefox's built-in Console object is compatible with the one provided by Firebug.

See alsoEDIT

  • Tools
  • Web Console — how the Web Console in Firefox handles console API calls
  • Remote debugging — how to see console output when the debugging target is a mobile device
  • On-device console logging — how to do logging on Firefox OS devices

Other implementations

  • Google Chrome DevTools
  • Firebug
  • Internet Explorer
  • Safari

文章来源
https://developer.mozilla.org/en-US/docs/Web/API/console

你可能感兴趣的:(所有,Web前端)