对象变量未在方法内更新
Object variable isn't updated inside a method
我正在尝试更新作为参数传递给打字稿代码中方法的对象,但它从未改变:
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
后获得新值。但是正如您在代码注释中看到的那样,变量在 replaceVariable
方法内部被替换,并在 myMethod
中保留一个 undefined
值
As objects are always passed by reference, I was expecting that myVariable gets the new value after calling the method replaceVariable
是的,它们是通过引用传递的。然而,它们 not 作为 out 变量传递。你可以改变,但你不能重新分配。
差异
由于 JavaScript 不支持 out 变量,这里是两者的 C# 参考,以便您了解差异:
我正在尝试更新作为参数传递给打字稿代码中方法的对象,但它从未改变:
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
后获得新值。但是正如您在代码注释中看到的那样,变量在 replaceVariable
方法内部被替换,并在 myMethod
undefined
值
As objects are always passed by reference, I was expecting that myVariable gets the new value after calling the method replaceVariable
是的,它们是通过引用传递的。然而,它们 not 作为 out 变量传递。你可以改变,但你不能重新分配。
差异
由于 JavaScript 不支持 out 变量,这里是两者的 C# 参考,以便您了解差异: