无法使用 for-in 循环更改对象 属性 值
Can't change object property values with for-in loop
我在 JavaScript / Vue.js 中遇到了一个奇怪的问题。我正在尝试遍历对象 (newGame) 的属性并将它们的值更改为 'undefined'。当我从 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);
},
}
重新分配标识符本身不会有任何副作用(在绝大多数情况下)- 除非您稍后使用标识符(此处为 property
),为其分配一些内容(例如 undefined
) 将无效。您需要将 undefined
分配给 newGame
对象`,以便实际改变对象:
for (let property in this.newGame) {
this.newGame[property] = undefined;
}
我在 JavaScript / Vue.js 中遇到了一个奇怪的问题。我正在尝试遍历对象 (newGame) 的属性并将它们的值更改为 'undefined'。当我从 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);
},
}
重新分配标识符本身不会有任何副作用(在绝大多数情况下)- 除非您稍后使用标识符(此处为 property
),为其分配一些内容(例如 undefined
) 将无效。您需要将 undefined
分配给 newGame
对象`,以便实际改变对象:
for (let property in this.newGame) {
this.newGame[property] = undefined;
}