检查对象的嵌套项的值

时间:2014-09-23 22:44:37

标签: javascript

我正在尝试检查周对象的分钟和小时,我无法弄清楚我做错了什么。周对象可以包含Day1 - Day7的变体,所以我不想特别检查它们。我想检查嵌套的小时/分钟。我也不想使用jquery,它必须使用ie8。任何帮助将不胜感激。

week = {
        Day1: {
            Hours: 6,
            Minutes: 20
        },
        Day2: {
            Minutes: 45
        },
        Day3: {
            Hours: 8,
            Minutes: 15
        }
    };

hoursInValid = false;
minutesInValid = false;

for (var item in week) {
        if (week.hasOwnProperty(item)) {
            for (var i = 0; i < week[item].length; i++ )
            {
                if (week[item][i].Hours > 6) {
                    hoursInValid = true;
                    break;
                }
                if (week[item][i].Minutes > 20) {
                    minutesInValid = true;
                    break;
                }

            }
        }
    }

3 个答案:

答案 0 :(得分:1)

请改为:

var invalidHours = {}, invalidMinutes = {};
for(var i in week){
  var w = week[i];
  if(w.hasOwnProperty('Hours')){
    invalidHours[i] = w.Hours > 6 ? true : false;
  }
  else{
    // no hours
  }
  if(w.hasOwnProperty('Minutes')){
    invalidMinutes[i] = w.Minutes > 20 ? true : false;
  }
  else{
    // no minutes
  }
}
if(invalidHours.Day1) // day 1 hours are invalid
if(invalidMinutes.Day2) // day 2 minutes are invalid

答案 1 :(得分:1)

我认为不需要内部for循环。这是我提出的解决方案。我添加了检查以确保DayN个对象具有HoursMinutes属性。

week = {
  Day1: {
    Hours: 6,
    Minutes: 20
  },
  Day2: {
    Minutes: 45
  },
  Day3: {
    Hours: 8,
    Minutes: 15
  }
};

hoursInValid = false;
minutesInValid = false;

for (var item in week) {
  if (week[item].hasOwnProperty('Hours')) {
    if (week[item].Hours > 6) {
      hoursInValid = true;
      break;
    }
  }
  if (week[item].hasOwnProperty('Minutes')) {
    if (week[item].Minutes > 20) {
      minutesInValid = true;
      break;
    }
  }
}

答案 2 :(得分:1)

试试这个:

for (var day in week) {
    for (var unit in week[day]) {
        if (unit === 'Hours' && week[day][unit] > 6) {
            hoursInvalid = true;
        } else if (unit === 'Minutes' && week[day][unit] > 20) {
            minutesInvalid = true;
        }
    }
}

break语句可能不允许您遍历所有属性。