我在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: undefinedgames: Array methods: {
addGame() {
let newGameCopy = { ...this.newGame };
newGameCopy.id = uuidv4()。
this.games = [...this.games, newGameCopy] 。
console.log(this.newGame)。
//span>這個不作業。
for (let propertyin this.newGame) {
console.log(property)。
property = undefined;
console.log(屬性)。
}
console.log(this.newGame) 。
//span>這個是有效的。
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) 。
},
uj5u.com熱心網友回復:
重新分配一個識別符號,本身不會有任何副作用(在絕大多數情況下)--除非你以后使用這個識別符號(這里是property),給它分配一些東西(比如undefined)將不會有任何影響。你需要將undefined賦值給newGame物件`,這樣才能真正突變該物件:
for (let property in this. newGame) {
this.newGame[property] = undefined。
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/327397.html
標籤:
