Javascript Javascript将对象推入数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2729323/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 01:41:09  来源:igfitidea点击:

Javascript pushing object into array

javascriptooparraysobjectpush

提问by Anonymous

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?

但它不起作用,没有任何回应。我究竟做错了什么?

回答by rahul

You have a typo in your code.

你的代码有错别字。

Change

改变

player = new array();

to

player = new Array();

回答by Jared Forsyth

I would do

我会做

player = [];

instead of

代替

player = new array();

As a sanity check, try doing:

作为健全性检查,请尝试执行以下操作:

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

回答by nc3b

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

好吧,你有一个错误。不是array但是Array

回答by Jan Michael Intia

I tried this and worked:

我试过这个并工作:

player = [{}];

instead of:

代替:

player = new Array();