gpt4 book ai didi

javascript - 增加计数器并动态更改依赖它的变量

转载 作者:行者123 更新时间:2023-11-30 09:22:18 24 4
gpt4 key购买 nike

我怎样才能递增一个计数器并期望递增的计数器在使用它的对象值内发生变化?

想象一下:

var pizzaOrder = {
id: "pizza",
counter: 0,
sentence: this.id + this.counter // first problem is here
// as I am getting NaN
};

pizzaOrder.counter++;

console.log(pizzaOrder.sentence);

预期输出:

"pizza1";

最佳答案

你不能像那样引用一个尚未完成创建的对象,但听起来你想在这里使用一个 getter:

var pizzaOrder = {
id: "pizza",
counter: 0,
get sentence() {
return this.id + this.counter;
}
};
pizzaOrder.counter++;

console.log(pizzaOrder.sentence);

关于javascript - 增加计数器并动态更改依赖它的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50905900/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com