0

I am programming in JavaScript and I created an array called users and a constructor for the user object. Everytime a new object is created I want to add it to the array.

var users = [];


function user(username, password){
    this.username = username;
    this.password = password;
    users[users.length-1] = this;
};

var joe = new user('Joe', "joe100");

The way above doesn't seem to work. How can I add an object to an array in the constructor?

1
  • Just get rid of the -1 Commented Jul 27, 2014 at 1:37

2 Answers 2

2

"users" is an empty array which means its length is 0 when you hit the constructor. So assigning "this" to length-1 would mean assigning "this" to the "-1" index...thats why it is not working....get rid of the -1, or...

Use the javascript array.push() function instead to add to your array perhaps

Check out the example on W3Schools site... Array#push

Sign up to request clarification or add additional context in comments.

Comments

1

Just remove -1 from your code and it will look like bellow one

var users = [];


function user(username, password){
    this.username = username;
    this.password = password;
    users[users.length] = this;
};

var joe = new user('Joe', "joe100");

An HTML Demo code example for you

<!DOCTYPE html>
<html>
<body>

<p id="demo"></p>

<script>
var users = [];


function user(username, password){
    this.username = username;
    this.password = password;
    users[users.length] = this;
};

var joe = new user('Joe', "joe100"),l = new user('ll', "ll99");

document.getElementById("demo").innerHTML = users[0].username+"   ---  "+users[0].password+"<br/>"+users[1].username+"   ---  "+users[1].password;
</script>

</body>
</html>

I think this will help you.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.