gpt4 book ai didi

javascript - 在 <script> 标签中声明一个 function() 是必要的吗?

转载 作者:行者123 更新时间:2023-11-28 06:07:27 25 4
gpt4 key购买 nike

我已经开始学习网络开发语言来制作网站。学过html和css。现在从 w3schools 网站学习 java 脚本。在学习函数时,我陷入了一个棘手的代码中。

    <!DOCTYPE html>
<html>
<body>

<p>A local variable can only be accessed from within the function where it was declared.</p>

<p id="demo"></p>

<script>
myFunction();
document.getElementById("demo").innerHTML =
"I can display " + typeof carName;

function myFunction() {
var carName = "Volvo";
}
</script>

</body>
</html>

所以我的问题是,为什么 myFunction();在脚本标签中声明?之前学过一些函数 block ,但是没遇到过这样的代码 EG:

<!DOCTYPE html>
<html>
<body>

<p>This example calls a function which performs a calculation, and returns the result:</p>

<p id="demo"></p>

<script>

function myFunction(a, b) {
return a * b;
}
document.getElementById("demo").innerHTML = myFunction(4, 3);
</script>

</body>
</html>

在这些代码中,函数名没有在脚本标签中声明。

最佳答案

调用一个函数,您必须先声明它。因此,在您的示例中,函数的声明是这样的:

function myFunction(a, b) {
return a * b;
}

这是调用:

document.getElementById("demo").innerHTML = myFunction(4, 3);

关于javascript - 在 &lt;script&gt; 标签中声明一个 function() 是必要的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36371916/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com