繁体   English   中英

Javascript 函数:更改单个变量 InPlace 的值

[英]Javascript function: change value of a single variable InPlace

函数 reverseArrayInPlace(array) 与 eloquentJS 中的解决方案相同。 reverseArrayInPlace 函数通过按预期更改 arrayValue 起作用。 为单个变量编写的类似函数无法按预期工作。 在代码中,x 应该是 25,但结果是 20。

//function from eloquentJS solutions, working as expected
``    function reverseArrayInPlace(array) {
      for (let i = 0; i < Math.floor(array.length / 2); i++) {
        let old = array[i];
        array[i] = array[array.length - 1 - i];
        array[array.length - 1 - i] = old;
      }
      return array;
    }
    let arrayValue = [1, 2, 3, 4, 5];
    reverseArrayInPlace(arrayValue);
    console.log(arrayValue);
    // working as expected, returns → [5, 4, 3, 2, 1]
    
    // Writing similar function for a single variable
    
    function changeInPlace(a) {
      a += 5;
      return a;
    }
    let x = 20;
    changeInPlace(x);
    console.log(x);
    // Not working as expected returns, 20 instead of 25

   

    
     
    
`     

代码片段

问题是您正在返回计算出的变量而不是记录它。 您正在记录的那个仍然是 20。

您必须使用您的功能如下:

let variable = changeInPlace(x)

完整代码必须如下:

function changeInPlace(a) {
  a += 5;
  return a;
}
let x = 20;
x = changeInPlace(x);
console.log(x);
// x should come out as 25

如果出于某种原因要直接编辑变量值,则必须像这样全局访问它:

function changeInPlace() {
    x += 5;
    return x;
}
let x = 20;
changeInPlace(x);
console.log(x);

将 changeInPlace 分配给倒数第二行的变量,然后在控制台中打印该变量。 它应该工作。

每次要更改变量中的值时,都需要以声明的形式再次调用它。 因此,函数的输出需要声明为变量 x 的新值。 像下面这样:

你的职能

// Writing similar function for a single variable

function changeInPlace(a) {
  a += 5;
  return a;
}
let x = 20;
changeInPlace(x);
console.log(x);
// x should come out as 25

// Writing similar function for a single variable

function changeInPlace(a) {
  return a += 5; // Made a small tweak to your function,
}
let x = 20;
x = changeInPlace(x); // this stores the output of the function in the same variable
console.log(x);

这应该给你想要的输出,假设这是你一直在要求的,否则让我知道

Marijn(eloquentJS 的作者)回答:您不能在 JavaScript 中更改数字,只能创建新数字,因此函数无法更改其作为参数传递给该函数的绑定的 例如,参见本书中的这一部分: https : //eloquentjavascript.net/04_data.html#h_C3n45IkMhg

暂无
暂无

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

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