简体   繁体   English

javascript范围:在函数后保留全局变量值

[英]javascript scope : retain global variable value after a function

When the 'hypotenuse' function is called the value of 'x' changes from 1. Fix it so that 'x' is still 1 in the gobal scope. 调用“斜边”功能时,“ x”的值从1更改。对其进行修复,以使“ x”在全局范围内仍为1。

  var x = 1;
  var y = 1;

  function hypotenuse(a , b) {
    var cSquared = a * a + b * b;
    x = Math.sqrt(cSquared);
    return x;
  }

  hypotenuse(x, y);

All you need to do to make this happen is redeclare the x variable using var within the function. 您需要做的就是在函数中使用var重新声明x变量。 This is will declare the x variable within the scope of the function, leaving the original, globally scoped x variable untouched: 这将在函数范围内声明x变量,而原始的全局范围内的x变量保持不变:

  var x = 1;
  var y = 1;

  function hypotenuse(a , b) {
    var cSquared = a * a + b * b,
        x = Math.sqrt(cSquared);
    return x;
  }

  hypotenuse(x, y);

Or, using the code style which you originally adopted (splitting out var declarations): 或者,使用最初采用的代码样式(拆分var声明):

  var x = 1;
  var y = 1;

  function hypotenuse(a , b) {
    var cSquared = a * a + b * b;
    var x = Math.sqrt(cSquared);
    return x;
  }

  hypotenuse(x, y);

For more detailed info on what is happening here, read up on javascript scope 有关此处发生的情况的更多详细信息,请阅读javascript范围

Try this: 尝试这个:

  var x = 1;
  var y = 1;

  function hypotenuse(a, b) {
    var cSquared = a * a + b * b;
    var x = Math.sqrt(cSquared);
    return x;
  }

  //console.log(hypotenuse(x, y));
  //console.log('x = ' + x);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM