当 y 发生变化时,如何保持其值取决于变量 y 的变量 x 更新?


function test(n) {
let y = 0
let x = y / 2
while (y < n) {
console.log('add');
y++;
}
console.log(y);
console.log(x);
}
test(6);
//x prints out 0 instead of 3

x应该随着y的变化而变化。如何使这些变量保持同步?

如果要使变量始终保持同步,则可以创建一个具有y的对象和用于xgetter方法,该方法返回依赖于当前值的值y

let obj = {
y: 0,
get x() {
return this.y / 2;
}
};
function test(n) {
while (obj.y < n) {
console.log("add");
obj.y++;
}
console.log(obj.y);
console.log(obj.x);
}
test(6);

没有什么可以自动执行此操作,您需要自己执行此操作。

while (y < n) {
console.log('add');
y++;
}
x = y/2;

如果第二个变量总是第一个变量的相同函数,你确定需要两个变量吗?

通常,最好的选择可能是在调用函数时使用函数来计算值,尤其是在进行廉价计算时。可以将其视为代数表达式。

请考虑以下事项:

function x(y) {
return y / 2
}
function test(n) {
let y = 0
while (y < n) {
console.log('add');
y++;
}
console.log(y);
console.log(x(y));
}
test(6);

如果 x 总是 y 的一半,那你为什么需要 X?

最新更新