javascript - 将变量存储在数组中(作为对象中的值) JavaScript
问题描述
我有一个简单的函数来检查用户名是否已经存在于对象数组中,如果确实存在,它应该以格式{用户名:用户名,时间:[第一次,第二次等]}将新时间保存在数组中。代码本身比较粗糙,但问题是如果用户名不存在(并且数组不为空,所以已经保存了一些其他用户名),如果我尝试相同的用户名,该函数会节省两次时间,我又得到了一个双倍的对象。
let array = []
const userName = prompt("username")
const userTime = prompt("points")
if (array.length > 0) {
for (let i = 0; i < array.length; i++) {
if (array[i].username === userName) {
array[i].time.push(userTime)
} else {
const thisTime = {
username: userName,
time: [userTime]
}
array.push(thisTime)
}
}
} else {
const firstTime = {
username: userName,
time: [userTime]
}
array.push(firstTime)
console.log(array)
}
所以在第一轮我得到 [{username: "maria", time: Array(1)}]
在第二轮使用另一个用户名 [{username: "maria", time: Array(1)}, {username: "ariana", time: Array(2) eg [14,14] (应该只有 1 个值)} ]
代码是根据规则编辑的,所以在游戏过程中添加了实际的用户名和时间。
解决方案
您可以使用更有效且不易出错的方式来做到这一点:
// look for the index in the array
const pointIndex = this.points.findIndex(point => point.username === this.username);
if(pointIndex > -1){ // if found, push the time
this.points[pointIndex].time.push(this.globalTime);
}
else { // push a new point otherwise
const thisTime = {
username: this.username,
time: [this.globalTime]
}
this.points.push(thisTime)
}
推荐阅读
- python - 如果在执行 iterrows 时匹配给定条件,则删除行
- vba - 在当前查看的页面上选择表格(不是当前选择的页面)
- ubuntu-16.04 - EAP-FAST 的 hostapd 基本配置?
- python - 有问题的 for 循环:重复打印包含目录中文件中的关键短语的行
- google-analytics - GTM 在会话期间保持相同的变量值
- javascript - 通过 reducer 获取相同的数据或空数据
- unity3d - 生成和显示数千个多边形的最佳实践
- javascript - React - 加载外部脚本的问题
- powershell - 用于填充描述字段的 Powershell 脚本
- for-loop - 使用 for 循环在 tkinter 中创建小部件网格