2016-10-06 76 views
1

我想写一个简单的脚本来显示生日和星期一祝贺。目标是用字符串匹配数组

1)得到当天的疗效。 2)将雇佣数据存储在数组中。 3)如果某些雇员姓名匹配变量名字日,则写入文件祝贺。请注意,当天有更多的名字可以庆祝指定日期,那么所有的雇员都必须获得祝贺。 4)同样的生日,更多的人可以在同一天庆祝生日。 5)如果名字/日期不符合我们的雇员名单,那么什么都不要做。

我所著这个

var today = new Date(); 
var dayMonth = new Date(); 
var day = today.getDate(); 
var month = today.getMonth()+1; 
var year = today.getFullYear(); 

today = day +'. '+ month+'. '+ year; 
dayMonth = day +'. '+ month+'.'; 

var employees = [ 
    ["Frank", "Jagger", "6. 10.", "1984"], 
    ["Ringo", "Lennon", "6. 10.", "1983"], 
    ["John", "Star", "4. 10", "1962"], 
    ["Mick", "Sinatra", "4. 10", "1961"] 
]; 


var nameday; 
var age = employees - year; 
var employeesName; 

switch (dayMonth) { 
    case"6. 10.": nameday = "Frank, Ringo, Steve"; break; 
    default: nameday = 0; 
} 


if (employees === nameday) { 
    document.write("' + employeesName + ' and ' + employeesName + ' nameday today. Congratulation!") 
} 

if (dayMonth === nameday) { 
    document.write("John Star is ' + age + ' tady and Mick Sinatra is ' + age + ' today. Congratulation!") 
} 

我知道这些代码的到底是错的,但我怎样才能从阵列得到正确的数据?我如何访问所有的名字,然后将其与数组匹配?

codepen http://codepen.io/anon/pen/rrpRmG?editors=0012

回答

1

我会改变你的员工的数组保存员工的每一天的数组的对象。

然后,您可以通过获取此对象中的日期道具来获取生日的员工列表!

下面是它如何工作的:

var employees = [ 
 
    ["Test", "Person", "7. 10.", "1234"], 
 
    ["Frank", "Jagger", "6. 10.", "1984"], 
 
    ["Ringo", "Lennon", "6. 10.", "1983"], 
 
    ["John", "Star", "4. 10", "1962"], 
 
    ["Mick", "Sinatra", "4. 10", "1961"] 
 
]; 
 

 
// Create birthday overview 
 
var birthdayOverview = employees.reduce(function(obj, employee) { 
 
    var birthday = employee[2]; 
 
    obj[birthday] = obj[birthday] || []; 
 
    obj[birthday].push(employee); 
 
    
 
    return obj; 
 
}, {}); 
 

 
// Find today's birthdays: 
 

 
var today = new Date(); 
 
var currentDay = today.getDate(); 
 
var currentMonth = today.getMonth() + 1; 
 
var currentDateFormatted = currentDay +'. '+ currentMonth+'.'; 
 

 
var birthdayToday = birthdayOverview[currentDateFormatted]; 
 

 
console.log(birthdayToday);