Javascript pushing object into array

北战南征 提交于 2020-01-12 14:18:22

问题


Hey, I currently am having trouble trying to get this to work. Here's a sample code of what I am trying. A lot has been taken out, but this should still contain the problem. I have an object, user, and an array, player. I am trying to make an array with the players in it, here:

function user(name, level, job, apparel)
{
 this.name = name;
 this.state = "alive";
 this.level = level;
 this.job = job;
 this.apparel = apparel;
}

player = new array();
player.push(new user("Main Player", 1, 1, "naked"));
document.write(player[0].name);

But it's not working, nothing's being echo'd. What am I doing wrong?


回答1:


I would do

player = [];

instead of

player = new array();

As a sanity check, try doing:

document.write("Name: " + player[0].name);



回答2:


You have a typo in your code.

Change

player = new array();

to

player = new Array();



回答3:


Well, you've got an error. It's not array but Array.




回答4:


I tried this and worked:

player = [{}];

instead of:

player = new Array();


来源:https://stackoverflow.com/questions/2729323/javascript-pushing-object-into-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!