我有简单的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 :(得分:2)
你只需要移动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" };
var students = [student1, student2, student3];
alert(students[1].FirstName);

答案 1 :(得分: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 :(得分:0)
您必须收到明确的错误
“未捕获的TypeError:无法读取未定义的属性'FirstName'”
在初始化student1,student2...
数组时使用它们之前定义变量students
。
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);