【发布时间】:2020-11-01 20:34:02
【问题描述】:
我正在为 JavaScript 做一个面向对象和方法创建的数组,我有一个问题:
我在点击“显示员工”按钮时显示所有员工的位置,包括他们的所有信息(顺便说一句,这都是虚构的),但是,我在提取个人用户的信息时遇到了困难,我该怎么做关于单击单个用户并仅提取该信息?
函数 = showEmployee();是我遇到问题的地方。
代码如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Lab 9-1: Employee Database</title>
<script language="JavaScript" type="text/javascript">
// Complete the employeeObject constructor
// Remember t o add a method called showEmployee
function employeeObject(name,department,extension) {[]
this.name = name;
this.department=department;
this.extension=extension;
this.showEmployee=showEmployee;
}
// Instantiate 3 instances of employeeObject
// Important - Start your array index numbers with 1
var employees = new Array();
employees[0] = "Select Employee";
employees[1] = new employeeObject("Mai Li", "Sales", 551);
employees[2] = new employeeObject("Maria Alvarez", "Human Resources", 441);
employees[3] = new employeeObject("Tom Smith", "Marketing", 331);
len = employees.length;
function showEmployee() {
var info = ""
// Complete the showEmployee() function
alert(info);
}
function showAllEmployees() {
var info = "";
for (var i = 1; i < len; i++) {
info += "Employee: " + employees[i].name + "\n";
info += "Department: " + employees[i].department + "\n";
info += "Extension: " + employees[i].extension + "\n\n";
}
alert(info);
}
//-->
</script>
</head>
<body>
<h3>Employee Database</h3>
<hr />
<form name="empForm" id="empForm">
<strong>Select name to view information:</strong>
<select name="empName" onchange="employees[this.selectedIndex].showEmployee();this.selectedIndex=0;">
<script language="JavaScript" type="text/javascript">
for (var i = 0; i < len; i++) {
if(i == 0) document.write("<option>" + employees[i]) + "</option>";
else document.write("<option>" + employees[i].name) + "</option>";
}
//
</script>
</select>
<p>
<input type="button" value="Show All Employees" onclick=
"showAllEmployees();" />
</p>
</form>
</body>
</html>
`
【问题讨论】:
-
你可以做一些非常类似于showAllEmployee的事情,只是不要使用数组和循环,而只使用一个员工对象。正如答案中已经建议的那样,这个函数应该属于“类”Employee,选择一个员工会调用它,你自然会有正确的值来显示。
-
这段代码的格式应该更好,因为它在当前状态下很难阅读。此外,最好将员工的构造函数重命名为
Employee(name,department,extension)。
标签: javascript arrays methods