我正在尝试制作一个程序,显示一个人累积的旅行里程数。这是我创建的功能:
function showmiles(event:MouseEvent):void {
var hintEmployee1:int;
var hintEmployee2:int;
hintEmployee1 = (employee.indexOf(txtFirstname.text));
hintEmployee2 = (employee.indexOf(txtLastname.text));
if ((hintEmployee1 != -1) && (hintEmployee2 != -1))
{
trace("yes")
}
else
{
trace ("no")
}
}
如果名为“employee”的数组每个对象只有一个单词,那么这应该有效。但是,我在数组中定义了这样的员工:
employee.push({firstname: Jamie, lastname: Hughes, milesweek1: 400, milesweek2: 670})
如果一个人的第一个名字(输入文本框txtFirstname)和姓氏(输入文本框txtLastname)在一个数组对象内部,没有程序扫描它们,我如何检测我的程序作为一个单独的对象?
答案 0 :(得分:0)
您需要循环使用array
并逐个测试每个object
,直到找到匹配项为止:
function showmiles(event:MouseEvent):void {
if (isEmployee(txtFirstname.text, txtLastname.text))
{
trace("yes")
}
else
{
trace ("no")
}
}
function isEmployee(firstName:String, lastName:String):Boolean
{
// I've pluralised the name of the array which is better I think
for (var i:int = 0; i < employees.length; i ++)
{
var employee:Object = employees[i];
if (employee.firstname == firstName && employee.lastName == lastName)
{
return true;
}
}
// Employee isn't in the array
return false;
}
如果您加入underscore library,则可以使用findWhere
函数更简洁地执行此操作:
// Return the first object where firstname and lastname properties match the values in the text fields
_.findWhere(employees, { firstname: txtFirstname.text, lastname: txtLastname.text });
我假设它只是一个拼写错误,但对象中的名称值是字符串,应该引用:
employee.push({firstname: "Jamie", lastname: "Hughes", milesweek1: 400, milesweek2: 670})