【问题标题】:how to call to the anonymous array in the objects property jquery?如何调用对象属性jquery中的匿名数组?
【发布时间】:2016-03-18 13:33:17
【问题描述】:

我使用构造函数来创建对象

function player(name,state,score,marker,combination) {
    this.name = name;
    this.state = state;
    this.score = score;
    this.marker = marker;
    this.combination = combination;
} 

属性“组合”应该是一个数组。在创建 PLAYER 对象实例时,我以这种方式设置数组:

players[players.length] = new player(name,false,0,'marker',[]);

然后我在“组合”属性里面动态设置数组的值,但是我不知道如何找到当前数组的长度

players[i].combination[ANONYMOUS ARRAY.length] = some value;

我发现我在这里遗漏了一些关键知识。请问有人可以帮我吗?建议在对象的属性中设置数组/处理这样的数组的正确方式???

【问题讨论】:

  • players[i].combination[players[i].combination.length] = some value; 或更好的players[i].combination.push(some value);
  • 谢谢,我使用了 push() 选项。这行得通!

标签: jquery arrays object properties


【解决方案1】:

应该是players[i].combination.length,因为players[i].combination 是对数组的引用:

players[i].combination[players[i].combination.length] = some_value;

当然也可以:

players[i].combination.push(some_value);

【讨论】:

  • 非常感谢您的明确回答和解释!我确实使用了 push() 选项,这很好用!
【解决方案2】:

我会使用 push() 而不是放置索引并猜测长度,所以不是:

players[players.length] = new player(name,false,0,'marker',[]);players.push(new player(name,false,0,'marker',[]);

而不是 players[i].combination[ANONYMOUS ARRAY.length] = some value; 我猜你知道'i'的值,做players[i].combination.push(some_value)

或者如果你不知道我,那么只需创建组合数组并在创建播放器时传递它

【讨论】:

  • 嘿,非常感谢!我投票赞成你的答案,我不能选择 2 个正确答案:-) 在这种情况下你是对的 - 我不需要知道数组的长度,我可以 push()。但在某些情况下,我认为可能需要 - 知道数组的长度。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-05
  • 2022-10-12
  • 1970-01-01
  • 2013-06-30
相关资源
最近更新 更多