2016-10-06 73 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);