使用字符串匹配数组

时间:2016-10-06 10:19:01

标签: javascript arrays

我想写一个简单的脚本来显示生日和名字祝贺。目标是

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 个答案:

答案 0 :(得分: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);