2012-10-10 36 views
1

我想創建一個使用javascript和html的網頁,它會從用戶處獲取許多學生的詳細信息,並將其動態存儲到數組中。 所以我想我需要的是一個可以動態給定值的數組數組。 我創建了一個頁面來獲取學生的詳細信息,如「名字」。 「姓氏」,「入場號碼」和「班級」。我創建了一個表單並獲得了這樣的值。如何在JavaScript中創建一個包含一組數組併爲其動態分配值的數組?

form = document.std_form; 
f_name=form.firstname.value ; 
l_name=form.lastname.value ; 
a_no=form.ad_number.value ; 
c_no=form.class_no.value ; 

f_name保持姓名等.. 現在我想創建保持陣列STD1,STD2,STD3等各保持單獨的學生的細節的陣列student_list。請告訴我如何創建這樣一個數組,以及我如何顯示每個元素。

回答

1

你可以有一個數組名稱student_list它擁有所有的學生和一個數組student其中持有個別學生。

var student_list = new Array(); // this will have to be initialized only once 

var student = new Array(); // create instances for students with every student being entered through form 

// code to populate student array 

student_list.push(student); // push students one by one in main list. Should be executed with each student being saved. 

請根據您的需要修改代碼。

你可以看看this看看如何遍歷它。

希望它可以幫助!

+0

非常感謝。你能告訴我如何創建數組學生,其中包含「名」,「姓」,「入場號碼」和「班級」字段?我只是想聲明數組,以便在用戶輸入時爲其動態分配值。 – Mathew

+0

當我們點擊像 「保存」 按鈕一些什麼的,執行該代碼每次: 'VAR學生=新的Array();' 然後 '形式= document.std_form;'' student.push( form.firstname.value);' 和各自的字段。 最後這樣做 'student_list.push(student);' – Cyclone

+0

因此,無論你在代碼中做什麼,只要在頂部創建一個數組,然後將表單值推入該數組中,然後將該數組推入student_list。然後你明白了。 – Cyclone

0

下面是一個例子。

[編輯]

var studentList = new Array(); 
var curStudent = new Object(); 

    var i, num; 

    num = getNumberOfRecordsToAdd(); // how ever it is that you know how many the user wants to add 

    for (i=0; i<n; i++) 
    { 
     curStudent.f_name = getFname(i); // however it is you retrieve these from where ever they are at the moment 
     curStudent.l_name = getLname(i); 
     curStudent.a_no = getAno(i); 
     curStudent.c_no = getCno(i); 
     studentList.push(curStudent); 
    } 

這個代碼將會給你項目的數組。每個項目是一個對象,其中有 4個字段。

即:

//Student1: 

    studentList[0]  // student 1 (student0) 
    studentList[0].f_name // student1's f_name 
    studentList[0].l_name // student1's l_name 


//Student2: 

    studentList[1]  // student2 
    studentList[1].a_no // student2's a_no 
    studentList[1].c_no // student2's c_no 
+0

謝謝,但我遇到了這個問題..其實我想要的是,我想 curStudent [1]存儲f_name,l_name等student1, curStudent [2]存儲f_name ,l_name等學生2, 等智慧..你能幫我嗎? – Mathew

+0

你想要一個_multi-dimensional_數組,對吧? curStudent用於保存每個學生的詳細信息,然後將其添加到學生列表中。你是否希望通過數組或姓名訪問每個學生的個人信息字段? – enhzflep

+0

請參閱更新的解決方案。 – enhzflep

相關問題