使用数组存储对象的属性

时间:2017-03-22 16:30:52

标签: javascript

我有一个数组,我想用它来存储属性。

例如:

player[0].name = bla1;
player[0].money = 130;

现在我创建了for循环,但是当我尝试将名称存储在其中时,我收到错误。

   var player = [];
   for(i=0; i < players; i++)
   {
     var x = i + 1;
     var nickName = document.getElementById('player' + x + 'name').value
     player[i].name = nickName;
     console.log(player[i].name);
   }

我在尝试添加属性时遇到错误:

 player[i].name = nickName;
 console.log(player[i].name)

3 个答案:

答案 0 :(得分:2)

首先没有长度,所以我不确定你到底是什么循环

for(i=0; i < players; i++)  <--

如果索引未定义,则需要将对象添加到空索引中。

player[i] = player[i] || {};  //If there is no player defined, add an object
player[i].name = nickName;

答案 1 :(得分:1)

您需要先创建对象,然后才能在其上放置属性:

var player = [];
for(i=0; i < players; i++)
{
    var x = i + 1;
    var nickName = document.getElementById('player' + x + 'name').value
    player[i] = {};                   // *** Create the object
    player[i].name = nickName;
    console.log(player[i].name);
}

虽然您正在使用它,但您可以在创建时添加该属性:

var player = [];
for(i=0; i < players; i++)
{
    var x = i + 1;
    var nickName = document.getElementById('player' + x + 'name').value
    player[i] = {
        name: nickName
    };
    console.log(player[i].name);
}

答案 2 :(得分:1)

您应首先将player [i]设置为对象。 所以它将是:

 var player = [];
 for(i=0; i < players; i++)
 {
   var x = i + 1;

   var nickName = document.getElementById('player' + x + 'name').value
   player[i] = player[i] || {};
   player[i].name = nickName;
   console.log(player[i].name);
 }