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

相關問題