【问题标题】:How to update value in object?如何更新对象中的值?
【发布时间】:2021-09-08 22:38:07
【问题描述】:

我使用 Typescript,我想更新对象中的值,但只有当语句为真时,如果语句为假,则旧值应该仍在此对象中,请查看代码:

isUpdated: boolean;

const updatedObject: Object = {
     updatedAt: isUpdated ? new Date() : "old value, nothing to change"
}

就像上面的例子一样,当isUpdated 为真时,我的updatedAt 应该从new Date() 更新为新值,但是当我的isUpdated 为假时,我还想拥有我的旧值对象中的值,我不想使用大的if 语句并为这个简单的操作创建大量代码,somoene 可以告诉我怎么做吗?

感谢您的帮助!

【问题讨论】:

  • 试着给出一个更大的图景,你现有的updatedObject在哪里?
  • 旧值从何而来?我没看到
  • 当您的对象的 any 属性发生更改时,您想设置updatedAt 吗?那么你可能想使用decorators...
  • @Cerbrus 嗯,不,这是工程过度
  • 那你到底想要做什么

标签: node.js typescript express


【解决方案1】:

当您为isUpdated 分配新值时,您需要设置 updatedAt。当您尝试访问它时,您不能这样做。

这样就可以了:

class MyClass {
    private _isUpdated: boolean;    
    get isUpdated(): boolean { return this._isUpdated; }    
    set isUpdated(value: boolean) {
        this.updatedAt = new Date();
        this._isUpdated = value;
    }

    updatedAt: Date;
}

【讨论】:

    猜你喜欢
    • 2021-06-12
    • 2017-11-08
    • 1970-01-01
    • 2021-07-17
    • 1970-01-01
    • 2021-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多