javascript “System.out.println”如何在 JS 中工作?... :)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10521768/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how does "System.out.println" work in JS?... :)
提问by YoniGeek
My background is in java and right now Im getting into learning Javascript. (I'm porting this java code that I made into javascript but it behaves a bit different than I expected?? If I use "console.log()" instead of "document.write" I'm NOT getting the same result..why?
我的背景是 Java,现在我正在学习 Javascript。(我正在将我制作的这个 java 代码移植到 javascript 中,但它的行为与我预期的有点不同??如果我使用“console.log()”而不是“document.write”,我不会得到相同的结果。 。为什么?
thanks 4 yr time! Some insight will be very appreciated!
感谢 4 年时间!一些见解将不胜感激!
var counter = 1;
function println(str) {
console.log(str);//
}
for (var i = 1; i <= 5; i++) {
for (var j = i; j < 5; j++) {
document.write("#");
// println("#");
}
for (var k = 1; k <= counter; k++) {
document.write("*");
// println("*");
}
document.write("<br/>");
//println(" "); <--- "\n" ?
counter+= 2; //
} // ends application
采纳答案by Nathan Taylor
document.write()
is for printing content to the page of your document, while console.log()
is used predominantly for diagnostic/debug information to be emitted in the console of your web browser. Specifically, document.write()
is intended to be consumed by the viewer of your page, while console.log()
is generally not.
document.write()
用于将内容打印到文档页面,而console.log()
主要用于在 Web 浏览器的控制台中发出的诊断/调试信息。具体来说,document.write()
旨在供您页面的查看者使用,而console.log()
通常不会。
回答by demee
Console.log logs stuff into browser console. Install Firebug (getfirebug.com) and you will see your logs.
Console.log 将内容记录到浏览器控制台中。安装 Firebug (getfirebug.com),您将看到您的日志。
Also there is nice description about how it works http://getfirebug.com/logging.
还有关于它是如何工作的很好的描述http://getfirebug.com/logging。
Also, using document.write is not really elegant, you can use it only on page load, and it's blocking whole page. You basically should not use it at all. If you try to use document.write after page is loaded, it will replace whole content of your document with your last "log".
此外,使用 document.write 并不是很优雅,您只能在页面加载时使用它,并且它会阻塞整个页面。你基本上不应该使用它。如果您在页面加载后尝试使用 document.write,它将用您最后的“日志”替换文档的全部内容。