-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).

nicael
  • 18,550
  • 13
  • 57
  • 90
sprth
  • 1
  • 1

1 Answers1

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
        );
});
David Thomas
  • 249,100
  • 51
  • 377
  • 410
Amit Joki
  • 58,320
  • 7
  • 77
  • 95
  • 1
    It might be worth showing how to use [`push()`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/push) correctly. – David Thomas Nov 08 '14 at 16:43
  • @DavidThomas ah! Thanks for the edit, forgot that. – Amit Joki Nov 08 '14 at 16:46
  • 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 – sprth Nov 08 '14 at 16:46
  • 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 :) – David Thomas Nov 08 '14 at 16:49