对象分配产生未定义的变量

时间:2018-07-10 05:15:53

标签: javascript

因此,我以前使用过Object.assign(),并获得了一些成功。但是,我现在实际上遇到了问题。我有一个对象:

let stats = {
      rounds: 0,
      userHits: 0,
      userDmgDelt: 0,
      userDmgTaken: 0,
      userCrits: 0,
      userMiss: 0,
      userDodge: 0,
      mobHits: 0,
      mobDmgDelt: 0,
      mobDmgTaken: 0,
      mobCrits: 0,
      mobMiss: 0,
      mobDodge: 0,
    };

然后我正在尝试这样做:

stats = Object.assign(stats, {
    userMiss: userMiss++,
});

我认为在函数内使用对象会根据其旧值(为0)对其进行定义。我想避免使用较长的 stats.Stat += 1,不是。

4 个答案:

答案 0 :(得分:1)

您应该使用++stats.userMiss来更新userMiss的值

let stats = {
      rounds: 0,
      userHits: 0,
      userDmgDelt: 0,
      userDmgTaken: 0,
      userCrits: 0,
      userMiss: 0,
      userDodge: 0,
      mobHits: 0,
      mobDmgDelt: 0,
      mobDmgTaken: 0,
      mobCrits: 0,
      mobMiss: 0,
      mobDodge: 0,
    };

stats = Object.assign(stats, {
    userMiss: ++stats.userMiss
});

console.log(stats)

答案 1 :(得分:1)

userMiss是在对象stats中定义的键。 因此,要访问该属性,您需要编写stats.userMiss

stats = Object.assign(stats, {
userMiss: stats.userMiss++,

});

答案 2 :(得分:1)

userMiss不是独立变量,因此表达式userMiss++不起作用。如果要使用Object.assign,则必须使用

let stats = {
  rounds: 0,
  userHits: 0,
  userDmgDelt: 0,
  userDmgTaken: 0,
  userCrits: 0,
  userMiss: 0,
  userDodge: 0,
  mobHits: 0,
  mobDmgDelt: 0,
  mobDmgTaken: 0,
  mobCrits: 0,
  mobMiss: 0,
  mobDodge: 0,
};
stats = Object.assign(stats, {
  userMiss: stats.userMiss + 1,
});
console.log(stats);

但是为什么不简单地增加属性,而完全避免使用Object.assign

let stats = {
  rounds: 0,
  userHits: 0,
  userDmgDelt: 0,
  userDmgTaken: 0,
  userCrits: 0,
  userMiss: 0,
  userDodge: 0,
  mobHits: 0,
  mobDmgDelt: 0,
  mobDmgTaken: 0,
  mobCrits: 0,
  mobMiss: 0,
  mobDodge: 0,
};
stats.userMiss++;
console.log(stats);

答案 3 :(得分:1)

恕我直言,这就是您想要做的:

let stats = {
  rounds: 0, userHits: 0, userDmgDelt: 0, userDmgTaken: 0, userCrits: 0, userMiss: 0, userDodge: 0, mobHits: 0, mobDmgDelt: 0, mobDmgTaken: 0, mobCrits: 0, mobMiss: 0, mobDodge: 0,
};

stats = Object.assign(stats, {
    userMiss: ++stats.userMiss
});

console.log(stats)

但是,这是一种更好的 immutable 方法:

let stats = {
      rounds: 0, userHits: 0, userDmgDelt: 0, userDmgTaken: 0, userCrits: 0, userMiss: 0, userDodge: 0, mobHits: 0, mobDmgDelt: 0, mobDmgTaken: 0, mobCrits: 0, mobMiss: 0, mobDodge: 0,
    };

let newStats = Object.assign({}, stats, {
    userMiss: ++stats.userMiss
});

console.log(newStats)

或者,您也可以像这样使用最新的ES6 object destructuring

let stats = {
  rounds: 0, userHits: 0, userDmgDelt: 0, userDmgTaken: 0, userCrits: 0, userMiss: 0, userDodge: 0, mobHits: 0, mobDmgDelt: 0, mobDmgTaken: 0, mobCrits: 0, mobMiss: 0, mobDodge: 0,
};

    let newStats = { ...stats, userMiss: ++stats.userMiss };

    console.log(newStats)