2017-08-14 86 views
0

我有簡單的JavaScript代碼工作,但警報不會在任何瀏覽器中工作 我的代碼是:的javascript:警報不會在任何瀏覽器爲什麼

function ChangeText(){ 
    document.getElementById("p1").innerHTML = "dorood"; 
    } 
    var students = [student1, student2, student3]; 
    var student1 ={FirstName:"saeed",LastNmae:"alavi",Age:"1992"}; 
    var student2 = { FirstName: "mohammad", LastNmae: "alavi", Age: "1992" }; 
    var student3 = { FirstName: "hosein", LastNmae: "alavi", Age: "1992" }; 
    alert(students[1].FirstName); 

回答

0

你一定會得到下面的錯誤是明顯的

"Uncaught TypeError: Cannot read property 'FirstName' of undefined"

初始化students陣列在使用之前定義的變量student1,student2...

function ChangeText() { 
 
    document.getElementById("p1").innerHTML = "dorood"; 
 
} 
 

 
var student1 = { 
 
    FirstName: "saeed", 
 
    LastNmae: "alavi", 
 
    Age: "1992" 
 
}; 
 
var student2 = { 
 
    FirstName: "mohammad", 
 
    LastNmae: "alavi", 
 
    Age: "1992" 
 
}; 
 
var student3 = { 
 
    FirstName: "hosein", 
 
    LastNmae: "alavi", 
 
    Age: "1992" 
 
}; 
 

 
var students = [student1, student2, student3]; 
 
console.log(students[1].FirstName);

1

您可以創建創建單個對象後,才排列。

function ChangeText() { 
 
    document.getElementById("p1").innerHTML = "dorood"; 
 
} 
 

 
var student1 = { 
 
    FirstName: "saeed", 
 
    LastNmae: "alavi", 
 
    Age: "1992" 
 
}; 
 
var student2 = { 
 
    FirstName: "mohammad", 
 
    LastNmae: "alavi", 
 
    Age: "1992" 
 
}; 
 
var student3 = { 
 
    FirstName: "hosein", 
 
    LastNmae: "alavi", 
 
    Age: "1992" 
 
}; 
 
var students = [student1, student2, student3]; 
 
alert(students[1].FirstName);

2

你只需要移動VAR學生= [student1,STUDENT2,學生三]您所指的變量未被分配。

var student1 ={FirstName:"saeed",LastNmae:"alavi",Age:"1992"}; 
 
    var student2 = { FirstName: "mohammad", LastNmae: "alavi", Age: "1992" }; 
 
    var student3 = { FirstName: "hosein", LastNmae: "alavi", Age: "1992" }; 
 
    var students = [student1, student2, student3]; 
 
    
 
    alert(students[1].FirstName); 
 

相關問題