console.log有什么用?

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


当前回答

除了上面提到的用法,console.log也可以在node.js中打印到终端。使用express(例如)创建的服务器可以使用console.log写入输出记录器文件。

其他回答

它会发布一个日志消息到浏览器的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,我建议您阅读它。(跟踪、组、分析、对象检查)。

希望这能有所帮助!

console.log与jQuery无关。

它将消息记录到调试控制台,例如Firebug。

在早期,JS调试是通过alert()函数执行的——现在这是一种过时的做法。

console.log()是一个函数,它在调试控制台(如Webkit或Firebug)上写入一条消息以记录日志。在浏览器中,你在屏幕上看不到任何东西。它将一条消息记录到调试控制台。它只在带有Firebug的Firefox和基于Webkit的浏览器(Chrome和Safari)中可用。它在所有IE版本中都不能很好地工作。

控制台对象是DOM的扩展。

console.log()应该仅在开发和调试期间在代码中使用。

将console.log()留在生产服务器上的javascript文件中被认为是一种坏习惯。

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实际上可以接受任意多的参数。

如果使用Firebug等工具检查代码,则可以查看记录到控制台的任何消息。假设你这样做:

console.log('Testing console');

当您访问Firebug(或您决定使用的任何工具来检查代码)中的控制台时,您将看到您告诉函数要记录的任何消息。当您想要查看函数是否正在执行,或者变量是否被正确传递/赋值时,这特别有用。实际上,它对于找出代码中的错误是很有价值的。