了解功能和数字

时间:2018-10-25 14:52:24

标签: javascript math

var a = 3;
var b = 5;
example(a, b);

function example(b, a) {
  var result = b - a;
  alert(result);
}

我的问题是看着我,虽然结果是2,但它的负数2可以解释为什么吗?

4 个答案:

答案 0 :(得分:1)

您已经颠倒了函数定义中的参数。

您在致电(a,b)时,会收到(b,a)。这意味着您正在通过:

 example(3,5)

并接收:

 (b=3, a=5)

然后您返回:

 (b-a) or (3-5)

即-2。

答案 1 :(得分:0)

函数中参数的实际名称无关紧要。您会感到困惑,因为无论您在哪里找到示例,它们都巧妙地颠倒了avar a = 3; var b = 5; example(a, b); function example(bacon, eggs) { var result = bacon - eggs; alert(result); } 的顺序。但是,参数中的名称仅在函数作用域中使用,不会影响其外部具有相同名称的变量。例如:

-2

还将返回a,因为我们传递给示例的第一个参数是b(3),第二个参数是3-5 = -2(5)和.data()。实例中的参数名称实际上是什么都没关系,记住这一点很重要。

答案 2 :(得分:0)

您的代码没有问题。问题出在您的代码讲授上。结果实际上是-2。在Chrome调试器或类似工具中调试代码

var a = 3; // a equals 3
var b = 5; // b equals 5
example(a, b); // Replacing variables this is the same as example(3,5)      
      
// Changing variables names so you don't get mixed up
function example(c, d) { 
   // Since you called example(3,5) then c = 3 and d = 5
   var result = c - d; // This results in -2
   alert(result);
}

答案 3 :(得分:0)

不要与变量名混淆,因为在js中,它按函数参数的 order 起作用,而不是函数的变量名。要获得所需的输出,即 2 ,请尝试这样。

example(b = 5, a = 3);

function example(b, a) {
  var result = b - a;
  alert(result);
}

enter image description here

如果您有任何疑问,请访问http://www.pythontutor.com/javascript.html,看看幕后发生了什么。