【问题标题】:Object variable isn't updated inside a method对象变量未在方法内更新
【发布时间】:2019-02-01 00:14:54
【问题描述】:

我正在尝试更新作为参数传递给我的打字稿代码中的方法的对象,但它永远不会改变:

export class MyClass {

  //...
  myMethod(array) {
    //...
    let myVariable: MyObject;
    array.forEach(currentElement => {
      if (someCondition) {
        this.replaceVariable(myVariable, currentElement);
      }
    });

    console.log(myVariable); // myVariable here is Undefined

    return myVariable;
  }

  private replaceVariable(variableToReplace: MyObject, newValue: MyObject) {
    if (variableToReplace == null) {
      variableToReplace = newValue;
    } else {
      if (someCondition) {
        variableToReplace = newValue;
      }
    }

    console.log(variableToReplace); // variableToReplace here is replaced by newValue
  }
}

由于对象总是通过引用传递,我期待myVariable 在调用方法replaceVariable 后获得新值。但正如您在代码 cmets 中看到的那样,变量在 replaceVariable 方法内被替换,并在 myMethod 中保留 undefined

【问题讨论】:

    标签: typescript pass-by-reference


    【解决方案1】:

    由于对象总是通过引用传递,我期待 myVariable 在调用方法 replaceVariable 后获得新值

    是的,它们是通过引用传递的。然而,它们 not 作为 out 变量传递。您可以变异,但不能重新分配。

    区别

    由于 JavaScript 不支持 out 变量,这里是两者的 C# 参考,以便您了解区别:

    【讨论】:

    • 感谢您的解释。我最终从replaceVariable 方法返回值并将其分配给变量实例myVariable
    • 完美选择???
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多