首页 > 解决方案 > 将变量存储在数组中(作为对象中的值) 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 个值)} ]

代码是根据规则编辑的,所以在游戏过程中添加了实际的用户名和时间。

标签: javascriptarraysobject

解决方案


您可以使用更有效且不易出错的方式来做到这一点:

// 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)
}

推荐阅读