2014-11-08 31 views
-2

我需要在javascript中插入一个对象作为数组元素。为前:如何在JavaScript中插入一个对象作为数组元素javascripts

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

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

我也使用getter方法返回values.But,下面的阵列中

var studentsArray = new Array(); 

我需要通过student1student2对象为studentsArray和显示学生姓名(查理和ERIC)。

+4

你尝试过在你自己解决这个? – Banana 2014-11-08 16:41:08

+0

我们可以在标题名称中将“javascripts”更正为“javascript”吗? – 2018-02-23 21:41:06

回答

1

你可以push它或只是使用文字。

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

打印的名称将是简单

studentsArray.forEach(function(student){ 
    alert(
      // display the appropriate property of student 
     ); 
}); 
+1

可能值得展示如何正确使用['push()'](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/push)。 – 2014-11-08 16:43:02

+0

@DavidThomas啊!感谢编辑,忘记了。 – 2014-11-08 16:46:23

+0

Thanku,在这里我使用了push()和文字符号。当我尝试使用控制台Array [Object,Object]打印这些值时,我得到了这样的结果 – sprth 2014-11-08 16:46:40

相关问题