console.log有什么用?
请用一个代码示例解释如何在JavaScript中使用它。
console.log有什么用?
请用一个代码示例解释如何在JavaScript中使用它。
当前回答
使用console.log向页面添加调试信息。
许多人使用alert(hasNinjas)来实现这一目的,但是console.log(hasNinjas)更容易使用。使用警报弹出一个模态对话框,阻止用户界面。
编辑:我同意巴蒂斯特·佩尔内特和扬·汉尼克的观点,检查窗口是一个非常好的主意。首先定义Console,以便在没有可用的控制台时代码不会中断。
其他回答
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进行调试时,我真的觉得web编程很容易。
var i;
如果我想检查i运行时的值..
console.log(i);
您可以在firebug的console选项卡中检查I的当前值。它是专门用于调试。
引用MDN文档
控制台-包含许多你可以调用来执行的方法 基本的调试任务,通常集中在各种日志记录上 值发送到浏览器的Web控制台。 到目前为止,最常用的方法是使用console.log 记录特定变量中包含的当前值。
如何使用Javascript?
let myString = 'Hello World';
console.log(myString);
还要记住控制台是web浏览器全局窗口对象的一部分。因此,以下内容在技术上也是正确的,但在实际场景中没有使用。
let myString = 'Hello World';
window.console.log(myString);
举个例子——假设你想知道哪行代码可以运行你的程序(在它崩溃之前!),只需输入
console.log("You made it to line 26. But then something went very, very wrong.")
除了上面提到的用法,console.log也可以在node.js中打印到终端。使用express(例如)创建的服务器可以使用console.log写入输出记录器文件。