console.log 和 return 为 html 做了什么?

What do console.log and return do for html?

当使用 onclick 事件时,在我的 javascript 代码中使用 "return" 和 "console.log" 什么都不做,而使用 document.write 例如会,所以我知道它不是代码。这可能是一个愚蠢的问题,但这是为什么呢?当我在 Codecademy 练习时,他们总是使用 console.log 或 return 并弹出答案。

myArray = [2000, 2200, 2300, 2400, 2600, 3000];
var rand = myArray[Math.floor(Math.random() * myArray.length)];

    function swimWorkout() {
        return rand;
    }
</head>
<body>
    <button onclick="swimWorkout();">Find the length </button>
</body>

console 是浏览器中的浏览器应用程序,仅写入浏览器的开发人员工具。该网站上的 console 也是如此。它只写入该站点的网页。它不会也不能更改 HTML 文档或 DOM.

document.write 是浏览器本身中的 javascript 运行,它通过 DOM.

写入 HTML 文档

“return”语句实际上指的是 returning 您将从函数的结束进程传递的值,“console.log”将记录您在浏览器开发工具中的控制台部分(在浏览器上按 F12 并转到控制台选项卡),例如

function foo() {
   // do something
   return “ran foo function”;
}

console.log(foo());

console.log() 将消息发送到控制台,而 document.write() 将内容添加到 html 文档。我没有使用过 Codeacademy,但我猜测控制台中的东西是 "popping up"(console.log 语句所在的地方)。每个浏览器都有一个控制台。例如,在 Chrome 中,导航到查看 -> 开发人员 -> Javascript 控制台以查看 console.log() 语句的输出。

这确实返回了文档所述的值,正如您所期望的那样:

function swimWorkout() {
    return rand;
}

但是,这并不是您所期望的那样:

<button onclick="swimWorkout();">Find the length </button>

当您单击该按钮时,将执行函数并返回值。但是在任何地方都没有关于如何使用该值 do 的说明。没有理由显示在任何地方,因为没有显示它的代码。

您已经找到一种可能显示某些内容的方法:

document.write(rand);

但是,这可能是一种有问题的方法。 document.write() 不能很好地控制您要在文档中的什么地方写东西。如果您有一些在页面加载时执行的内联 JavaScript,它应该就在原处输出。但是在那之后的任何事情都可能不会写在你想要的地方。

相反,您可以使用其他 JavaScript 代码来 select 一个元素并输出到它。例如,考虑这样的事情:

myArray = [2000, 2200, 2300, 2400, 2600, 3000];
var rand = myArray[Math.floor(Math.random() * myArray.length)];

function swimWorkout() {
    document.getElementById('output').innerText = rand;
}
<button onclick="swimWorkout();">Find the value</button>
<p>The value is: <span id="output"></span></p>

您可以通过绑定到单击事件而不是在 HTML 中内联编写函数调用来进一步将 JavaScript 与 HTML 分离(也推荐):

myArray = [2000, 2200, 2300, 2400, 2600, 3000];
var rand = myArray[Math.floor(Math.random() * myArray.length)];

function swimWorkout() {
    document.getElementById('output').innerText = rand;
}

document.getElementById('find-value').addEventListener('click', swimWorkout);
<button id="find-value">Find the value</button>
<p>The value is: <span id="output"></span></p>

保持标记和逻辑快速分离变得更容易整体维护。