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

其他回答

console.log()是JavaScript中的一个函数,用于打印之前在其中定义的任何类型的变量,或者只是打印需要显示给用户的任何消息。

如代码:

function func() { return (5 * 18); }
     console.log(func());

IMG:

输出:

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

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

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

console.log('Testing console');

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

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

var variable;

console.log(variable);

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

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

这与jQuery无关。console.log()引用控制台对象的日志函数,该函数提供了将信息记录到浏览器控制台的方法。这些方法仅用于调试目的,不应依赖于将信息呈现给最终用户。