-2

I need to insert an object as an array element in javascripts. for ex:

var student1 = new Student();
student1.setStudentName("Charlie"); //set method

var student2 = new Student();
student2.setStudentName(10);

I also use getter method to return the values.But, in the following array

var studentsArray = new Array();

I need to pass student1 and student2 objects into studentsArray and display student names(Charlie and Eric).

2
  • 4
    have you tried solving this on your own? Commented Nov 8, 2014 at 16:41
  • can we get "javascripts" corrected to "javascript" in the title name? Commented Feb 23, 2018 at 21:41

1 Answer 1

1

You can push it or just use the literal.

var studentsArray = [student1, student2];
// or studentArray.push(student1, student2);

Printing the names would be simple

studentsArray.forEach(function(student){
   alert(
          // display the appropriate property of student
        );
});
Sign up to request clarification or add additional context in comments.

4 Comments

It might be worth showing how to use push() correctly.
@DavidThomas ah! Thanks for the edit, forgot that.
Thanku,here I have used both the push() and literal notation.When I try to print those values using console Array [ Object, Object ] I am getting like this
Yes, because you're trying to print an Object, which calls toString() on the whole object; what you should (probably) do is print the properties of an object console.log(student.name) (presumably). And, Amit, no problem at all :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.