简体   繁体   English

console.log和javaScript中return的区别

[英]The difference between console.log and return in javaScript

So I created two different functions to build triangles out of asterisks: buildTriangle and buildTriangle2. 因此,我创建了两个不同的函数以用星号构建三角形:buildTriangle和buildTriangle2。 The makeLine function is just used to make the lines in the triangles. makeLine函数仅用于制作三角形中的线。 This is what my code looks like: 这是我的代码如下所示:

 function makeLine(length) { var line = ""; for (var j = 1; j <= length; j++) { line += "* " } return line + "\\n"; } // This is the build triangle function with the return key function buildTriangle(triWidth) { var y = "" for(var i = 0; i <= triWidth; i++) { y += makeLine(i) } return y; } console.log(buildTriangle(10)) // This is the build triangle function with console.log function buildTriangle2(triWidth) { for(var i = 0; i <= triWidth; i++) { console.log(makeLine(i)); } } buildTriangle2(10) 

The output looks like this: https://i.stack.imgur.com/QrHxO.png . 输出看起来像这样: https : //i.stack.imgur.com/QrHxO.png First, I just had a quick question as to why there are spaces between each line in the second output and not in the first. 首先,我只是简单地问了一个问题,为什么第二个输出中的每一行之间都没有空格,而第一行中却没有。 Also, I just wanted to know why the the function with the return key needs to store the information in the variable first and then return it? 另外,我只是想知道为什么带有返回键的函数需要先将信息存储在变量中然后返回它? Why is this not the case in the second function that uses the console.log? 为什么在使用console.log的第二个函数中不是这种情况? I am asking this question because I think these two functions illustrate the differences between console.log and return. 我问这个问题是因为我认为这两个函数说明了console.log和return之间的区别。 Also, since I don't understand the difference between console.log and return I was hoping someone could explain it by using these functions. 另外,由于我不了解console.log和return之间的区别,我希望有人可以通过使用这些功能来解释它。 I also believe this will help other beginners besides for myself. 我还相信,这对自己以外的其他初学者也会有所帮助。

return doesn't do anything to the value, so you build what you want and you get exactly that. return对价值没有任何作用,因此您可以构建自己想要的东西,而您得到的正是。

console.log() is meant for outputting stuff (mainly for development purposes originally, but now with things like Node.js, also for general output). console.log()用于输出内容(最初主要用于开发目的,但现在带有Node.js之类的东西,也用于常规输出)。

In most environments, console.log() will always include a newline on it's own (similar to other languages println() functions). 在大多数环境中, console.log()总是会自己包含一个换行符(类似于其他语言的println()函数)。

That's why you need to have the \\n for the return, and not for console.log() , since it is basically adding one to each line for you. 这就是为什么您需要使用\\n而不是console.log() ,因为它基本上是为您在每行中添加一个。 If you add an extra \\n yourself, you'll end up with a blank line. 如果您自己添加一个\\n ,则将以空行结尾。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM