Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript pushing object into array

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?

like image 622
Anonymous Avatar asked Apr 28 '10 12:04

Anonymous


People also ask

Can you push an object into an array JavaScript?

To push an object into an array, call the push() method, passing it the object as a parameter. For example, arr. push({name: 'Tom'}) pushes the object into the array. The push method adds one or more elements to the end of the array.

How do you push an item to an array?

JavaScript Array push()The push() method adds new items to the end of an array. The push() method changes the length of the array. The push() method returns the new length.

How do you push an object with a key in an array?

To achieve this, we'll use the push method. As you can see, we simply pass the obj object to the push() method and it will add it to the end of the array. To add multiple objects to an array, you can pass multiple objects as arguments to the push() method, which will add all of the items to the end of the array.

How do you push an object in JavaScript?

In order to push an array into the object in JavaScript, we need to utilize the push() function. With the help of Array push function this task is so much easy to achieve. push() function: The array push() function adds one or more values to the end of the array and returns the new length.

How do you push an array of objects into another array?

To append one array to another, use the push() method on the first array, passing it the values of the second array. The push method is used to add one or more elements to the end of an array. The method changes the contents of the original array.


4 Answers

You have a typo in your code.

Change

player = new array();

to

player = new Array();
like image 139
rahul Avatar answered Sep 24 '22 18:09

rahul


I would do

player = [];

instead of

player = new array();

As a sanity check, try doing:

document.write("Name: " + player[0].name);
like image 28
Jared Forsyth Avatar answered Sep 22 '22 18:09

Jared Forsyth


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

like image 26
nc3b Avatar answered Sep 23 '22 18:09

nc3b


I tried this and worked:

player = [{}];

instead of:

player = new Array();
like image 42
Jan Michael Intia Avatar answered Sep 25 '22 18:09

Jan Michael Intia