【问题标题】:Can't change object property values with for-in loop无法使用 for-in 循环更改对象属性值
【发布时间】:2021-11-13 18:34:08
【问题描述】:

我在 JavaScript / Vue.js 中遇到了一个奇怪的问题。我正在尝试遍历对象(newGame)的属性并将它们的值更改为“未定义”。当我从 for 循环内部对它们进行 console.log() 时,它们似乎获取了值,但在循环之后有点“恢复”到它们以前的值。我很确定我在这里忽略了一些东西。 newGame 的属性也通过 v-model 绑定到一些输入元素。 这是sn-p的代码:

data() {
    return {
        newGame: {
            id: undefined,
            date: undefined,
            location: undefined,
            length: undefined,
            limit: undefined,
            buyIn: undefined,
            cashOut: undefined
        },
        games: Array
    };
},
methods: {
    addGame() {
        let newGameCopy = { ...this.newGame };
        newGameCopy.id = uuidv4();
        this.games = [...this.games, newGameCopy];

        console.log(this.newGame);

        // This one doesn't work.
        for (let property in this.newGame) {
            console.log(property);
            property = undefined;
            console.log(property);
        }
        console.log(this.newGame);

        // This one works.
        this.newGame.id = undefined;
        this.newGame.date = undefined;
        this.newGame.length = undefined;
        this.newGame.limit = undefined;
        this.newGame.buyIn = undefined;
        this.newGame.cashOut = undefined;
        this.newGame.location = undefined;

        console.log(this.newGame);
    },
}

【问题讨论】:

    标签: javascript vue.js for-loop this javascript-objects


    【解决方案1】:

    重新分配标识符本身不会产生任何副作用(在绝大多数情况下)-除非您稍后使用标识符(此处为property),否则为其分配某些内容(如undefined)将没有效果。您需要将undefined 分配给newGame 对象`,以便真正改变对象:

    for (let property in this.newGame) {
      this.newGame[property] = undefined;
    }
    

    【讨论】:

    • 谢谢,我现在明白了,而且效果很好! :)
    猜你喜欢
    • 2015-03-16
    • 2013-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-02
    • 1970-01-01
    • 1970-01-01
    • 2014-10-26
    相关资源
    最近更新 更多