javascript - 无法使用 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);
},
}
解决方案
重新分配标识符本身不会产生任何副作用(在绝大多数情况下) - 除非您property
稍后使用标识符(此处为 ),否则为其分配某些内容(如undefined
)将无效。您需要分配undefined
给newGame
对象`,以便实际改变对象:
for (let property in this.newGame) {
this.newGame[property] = undefined;
}
推荐阅读
- javascript - 动态设置元标签 EJS
- javascript - header 和 location.href 不会加载另一个页面,而是使用根目录
- unity3d - Unity 项目无法使用 Mono 构建
- google-apps-script - 如何更改 new Date() 的格式并将结果与静态时间字符串组合
- java - 如何在一个数组列表中对两个不同的模型进行排序?
- c# - 为什么在try and catch中使用not显示时返回true?
- java - 使用 NativeModules 时在本机反应中“必须被捕获或声明为被抛出”
- debugging - Linux 上是否有 libc.a 的调试版本,例如 Windows 上的 libcmtd.lib?
- html - 创建父子数据的嵌套下拉菜单
- javascript - 使用存储在数组中的 JS 颜色值来设置 P5.js Dom 元素的样式