首页 > 解决方案 > 无法使用 for-in 循环更改对象属性值

问题描述

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

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);
    },
}

标签: javascriptvue.jsfor-loopthisjavascript-objects

解决方案


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

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

推荐阅读