console.log有什么用?

请用一个代码示例解释如何在JavaScript中使用它。


当前回答

在java脚本中,没有输入和输出函数。因此使用console.log()方法来调试代码。它是一种日志记录方法。它将在控制台日志(开发工具)下打印。

在打开IE开发工具之前,它不会出现在IE8及以下版本。

其他回答

如果您的浏览器支持调试,您可以使用console.log()方法来显示JavaScript值。

用F12激活浏览器中的调试,并在调试器菜单中选择“控制台”。

JavaScript中的控制台。尝试修复或“调试”一个不起作用的JavaScript程序,并练习使用console.log()命令。根据你所使用的浏览器,有一些快捷方式可以帮助你访问JavaScript控制台:

Chrome控制台键盘快捷键

Windows操作系统:Ctrl + Shift + J Mac: Cmd + Option + J

Firefox控制台键盘快捷键

Windows: Ctrl + Shift + K Mac: Cmd + Option + K

Internet Explorer控制台键盘快捷键

F12键

Safari控制台键盘快捷键

Cmd + Option + C

您可以使用它在Firefox的Firebug或WebKit浏览器的JavaScript控制台中调试JavaScript代码。

var variable;

console.log(variable);

它将显示变量的内容,即使它是一个数组或对象。

它类似于print_r($var);PHP。

A point of confusion sometimes is that to log a text message along with the contents of one of your objects using console.log, you have to pass each one of the two as a different argument. This means that you have to separate them by commas because if you were to use the + operator to concatenate the outputs, this would implicitly call the .toString() method of your object. This in most cases is not explicitly overriden and the default implementation inherited by Object doesn't provide any useful information.

在控制台尝试的例子:

>>> var myObj = {foo: 'bar'}
undefined
>>> console.log('myObj is: ', myObj);
myObj is: Object { foo= "bar"}

然而,如果你试图连接信息文本消息与对象的内容,你会得到:

>>> console.log('myObj is: ' + myObj);
myObj is: [object Object]

请记住,console。log实际上可以接受任意多的参数。

console.log将调试信息记录到某些浏览器(安装了Firebug的Firefox, Chrome, IE8,任何安装了Firebug Lite的浏览器)的控制台。在Firefox上,它是一个非常强大的工具,允许您检查对象或HTML元素的布局或其他属性。它与jQuery无关,但在使用jQuery时,通常会做两件事:

为Firebug安装firerequery扩展。除了其他优点外,这使得jQuery对象的日志记录看起来更好。 创建一个更符合jQuery链接代码约定的包装器。

这通常是这样的意思:

$.fn.log = function() {
    if (window.console && console.log) {
        console.log(this);
    }
    return this;
}

你可以调用它,比如

$('foo.bar').find(':baz').log().hide();

轻松检查jQuery链内部。

它会发布一个日志消息到浏览器的javascript控制台,例如Firebug或开发者工具(Chrome / Safari),并将显示执行它的行和文件。

此外,当你输出一个jQuery对象时,它会在DOM中包含对该元素的引用,点击它就会在Elements/HTML选项卡中找到该元素。

您可以使用各种方法,但要注意,要在Firefox中工作,必须打开Firebug,否则整个页面将崩溃。无论你记录的是一个变量、数组、对象还是DOM元素,它都会给你一个完整的分解,包括对象的原型(总是有趣的)。您还可以包含任意数量的参数,它们将被空格替换。

console.log(  myvar, "Logged!");
console.info( myvar, "Logged!");
console.warn( myvar, "Logged!");
console.debug(myvar, "Logged!");
console.error(myvar, "Logged!");

每个命令都显示不同的标识。

你也可以使用console.profile(profileName);开始分析一个函数,脚本等。然后用console.profileEnd(profileName)结束它;它会显示在你的Chrome配置文件选项卡(不知道与FF)。

要获得完整的参考,请访问http://getfirebug.com/logging,我建议您阅读它。(跟踪、组、分析、对象检查)。

希望这能有所帮助!