console.log有什么用?

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


当前回答

它不是jQuery特性,而是用于调试的特性。例如,当发生一些事情时,您可以将一些事情记录到控制台。例如:

$('#someButton').click(function() {
  console.log('#someButton was clicked');
  // do something
});

当你点击按钮时,你会看到#someButton在Firebug的“控制台”选项卡(或其他工具的控制台-例如Chrome的Web检查器)中被点击。

由于某些原因,控制台对象可能不可用。然后你可以检查它是否正确——这很有用,因为当你部署到生产环境时,你不必删除调试代码:

if (window.console && window.console.log) {
  // console is available
}

其他回答

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控制台。主要用途是调试JavaScript代码。

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链内部。

log是开发人员编写代码的一种方法,它可以不引人注目地通知开发人员代码正在做什么。它可以用来提醒您存在问题,但在调试代码时不应该取代交互式调试器。它的异步性质意味着记录的值不一定代表调用方法时的值。

简而言之:使用console.log(如果可用)记录错误,然后使用您选择的调试器:Firebug, WebKit开发工具(Safari和Chrome内置),IE开发工具或Visual Studio修复错误。

console.log与jQuery无关。它是由调试器(包括Chrome调试器和Firebug)提供的一个通用对象/方法,允许脚本将数据(或大多数情况下的对象)记录到JavaScript控制台。