【问题标题】:Failing to add objects to an empty array in javascript [closed]无法在javascript中将对象添加到空数组[关闭]
【发布时间】:2021-08-15 11:22:43
【问题描述】:

所以我有一个空数组,我想添加具有在运行时确定的值的对象。我想出了这段代码:

var res = []; //the result array which needs to be populated
var rn = Math.random() * 5;
var value1 = rn * 75,
  value2 = rn * 27.91;
let galf = {
  type: rn;
  v1l: Math.floor(value1 / 7);
  v2r: value2 % 7;
}
res.push(galf);
console.log(res)

现在看来,我对 galf 对象的声明是不稳定的。如果我注释掉这个声明,那么代码运行良好。

如果要在运行时确定对象的值,如何将对象正确添加到数组中?

【问题讨论】:

  • 我给你做了一个sn-p。它抛出的错误非常有用。正如 LeeLenalee 所说You shouldnt use ; in an object, to add more fields you need to use the , to separate fields

标签: javascript arrays javascript-objects


【解决方案1】:

您不应该在对象中使用;,要添加更多字段,您需要使用, 来分隔字段

var res = []; //the result array which needs to be populated
var rn = Math.random() * 5;
var value1 = rn * 75,
  value2 = rn * 27.91;

let galf = {
  type: rn,
  v1l: Math.floor(value1 / 7),
  v2r: value2 % 7,
}

res.push(galf);

console.log(res)

【讨论】:

  • 真的值得回答吗?
  • 真的值得投反对票 :),我们都会犯错误,如果我犯了错误会很高兴有人指出它们
  • You shouldnt use ; in an object, to add more fields you need to use the , to seperate fields 添加为评论并投票关闭,因为在这里输入错字是正确的做法
  • @mplungjan 很好,如果不是拼写错误?也许用户只是不知道语法?
  • Typo-type - 来吧,允许 op 删除这个问题
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-11-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多