动态创建if条件

时间:2016-04-21 20:29:33

标签: javascript if-statement arguments conditional-statements

我有以下数组,并且我创建了一个函数,用于根据传递的过滤器从数组中返回项目。

var students = [
    //name      grade   room        gender
    ["name1",   80,     "Farabi",   "K"],
    ["name2",   73,     "B1",       "K"],
    ["name3",   73,     "B1",       "K"],
    ["name4",   60,     "Farabi",   "K"],
    ["name5",   80,     "B1",       "E"],
    ["name6",   43,     "Farabi",   "E"],
];

function getGrades() {
    var grades = [];
    for (var i = 0; i < students.length; i++) {
        if (students[i][arguments[0][1]] == arguments[0][0]) {
            grades.push(students[i][1]);
        }
    }
    return grades;
}

getGrades(["E", 3]); // [gender, column index]

只要我通过一个过滤器,这就有效。如果我想传递两个过滤器,例如,getGrades(["E", 3], ["B1", 2])它就无法工作。

我需要一种方法来根据传递的参数配置(扩展)if条件students[i][arguments[0][1]] == arguments[0][0]

对于getGrades(["E", 3], ["B1", 2]),条件应为

students[i][arguments[0][1]] == arguments[0][0] && students[i][arguments[1][1]] == arguments[1][0]

如何动态创建if条件?

2 个答案:

答案 0 :(得分:1)

您可以遍历每个参数并单独检查它们,而不是尝试动态创建if条件。如果其中一个失败,它们都会失败。同样,如果它们都没有失败,您就知道总结果是有效的。

for (var i = 0; i < students.length; i++) {
  var student = students[i];
  var matched = true; // This won't change if all of the conditions pass
  for (var j = 0; j < arguments.length; j++) {
    var filter = arguments[j];
    if (student[filter[1]] !== filter[0]) {
      matched = false; // One of the conditions failed, don't check the rest
      break;
    }
  }
  if (matched) {
    grades.push(student[1]);
  }
}

答案 1 :(得分:0)

使用Functional Programming

的替代getGrades实施

var students = [
    //name      grade   room        gender
    ["name1",   80,     "Farabi",   "K"],
    ["name2",   73,     "B1",       "K"],
    ["name3",   73,     "B1",       "K"],
    ["name4",   60,     "Farabi",   "K"],
    ["name5",   80,     "B1",       "E"],
    ["name6",   43,     "Farabi",   "E"],
];


function getGrades(){
  var filters = Array.prototype.slice.call(arguments); //converts all passed filters to array
  return filters.reduce(function(result,filter){       //result is filtered student list till now
      return result.filter(function(student){          //return new filtered list
        return student[filter[1]] === filter[0];
      });
  },students).map(function(student){                   //map filtered students to their grades
      return student[1];
  })
}

document.write(getGrades(["E", 3], ["B1", 2]));