JavaScript函数未按要求工作

JavaScript function is not working as per requirement

本文关键字:工作 函数 JavaScript      更新时间:2024-01-13

根据学习和尝试,我正在研究非常简单的函数,以了解JavaScript函数的特性。但在创建函数后,我遇到了一些问题,我希望有人能帮助我解决以下问题。

问题是:-

a) 为什么浏览器中的console.log显示ReferenceError:c未定义?
b) 为什么p id="demo"无法显示结果?
c) 为什么提醒(c);一旦浏览器加载/刷新,函数外部是否不显示结果?
d)为什么返回(c);不工作?

function show(a, b){
  
  var c = a+b;
  alert(c);
  console.log(c);
  return(c);
  
}
alert(c);
document.getElementById("demo").innerHTML = c;        
<p onclick="show(10, 20)" >This example calls a function which performs a calculation, and returns the result:</p>
<p id="demo"></p>

因为javascript中的函数大括号定义了scope,并且在其内部声明的所有变量在其外部都不可见。所以c在你提醒它的地方是未定义的。

function show(a, b){
   var c;
   //'c' is visible only in the function
}

正如我在评论中所说:

如果在函数中定义c,则仅在函数中定义

你可以这样做:

HTML

<p onclick="show(10, 20)" >This example calls a function which performs a calculation, and returns the result:</p>
<p id="demo"></p>

JS-

    function show(a, b){
      var c = a+b;
      document.getElementById("demo").innerHTML = c; 
    }

变量c是函数show的本地变量。所以当你把它称为功能之外的时候,

您会得到错误ReferenceError:c未定义由于c什么都不是,p demo没有显示任何

    function show(a, b){
      
      var c = a+b;
      return(c);
      
    }
    var d = show(10,20);
    document.getElementById("demo").innerHTML = d; 
    <p onclick="show(10, 20)" >This example calls a function which performs a calculation, and returns the result:</p>
    <p id="demo"></p>

试试这个:-

        var c = "10";
        function show(a, b){
  
            c = a+b;
            alert(c);
            console.log(c);
            document.getElementById("demo").innerHTML = c;  
        }       
        window.onload = function () {
            document.getElementById("demo").innerHTML = c;
        };
    
    
<p onclick="show(10, 20)">This example calls a function which performs a calculation, and returns the result:</p>
    <p id="demo"></p>