JavaScript函数不符合要求

时间:2015-02-19 11:14:23

标签: javascript

根据学习和尝试我正在研究非常简单的函数来理解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>
&#13;
&#13;
&#13;

5 个答案:

答案 0 :(得分:2)

因为javascript中的函数括号定义scope,并且在其中声明的所有变量都不可见。 因此c未定义,您可以提醒它。

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

答案 1 :(得分:2)

正如我在评论中所说:

如果在函数中定义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; 

    }

答案 2 :(得分:1)

变量c是函数show的本地。所以当你在函数之外调用它时,

您收到错误ReferenceError:c未定义 并且由于c不算什么,p demo没有显示任何内容

答案 3 :(得分:1)

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

    <p id="demo"></p>
&#13;
&#13;
&#13;

答案 4 :(得分:0)

试试这个: -

&#13;
&#13;
        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;
        };
    
    
&#13;
<p onclick="show(10, 20)">This example calls a function which performs a calculation, and returns the result:</p>

    <p id="demo"></p>
&#13;
&#13;
&#13;