2 回答
TA贡献2051条经验 获得超10个赞
您的一些错误是
1。您正在将 (int)age 与 (array)grade 进行比较 最好的方法是age < grade.length
2。grade数组的索引是从 0 到 5,即grade[0] == [6, 'Grade 1'],这意味着如果年龄大于 5,你不会有结果。
另一种方法,如果你真的想打印出与年龄对应的等级,
// age = 7;
let yourGrade = grade.find(e => {
return e[0] == age;
});
// console.log(yourGrade); // [7, 'Grade 2']
// console.log(yourGrade ? yourGrade[1] : "You’re either too young or too old");
// Grade 2
上面的代码尝试查看您的(数组)等级并返回第一个项目等于计算年龄的值的第一次出现。
有很多方法可以实现这一目标。
编辑
或者,如果您对while循环特别感兴趣,您可以执行以下操作:
//age = 7;
let yourGrade;
let i = grade.length;
while(i––) {
if (grade[i][0] == age) {
yourGrade = grade[i];
break;
}
}
console.log(yourGrade);
//[7,'Grade 2']
//try with age = 5 //undefined
TA贡献1839条经验 获得超15个赞
如果您正在寻找年龄和年级,这可能是您的最佳解决方案。
请记住,这里的等级是二维数组,您将等级的第一个索引元素与年龄进行比较。所以你需要首先从等级数组的第一个元素中找到最大值。
var dob = '20120810';
var year = Number(dob.substr(0, 4));
var month = Number(dob.substr(4, 2)) - 1;
var day = Number(dob.substr(6, 2));
var today = new Date();
var age = today.getFullYear() - year;
if (today.getMonth() < month || (today.getMonth() == month && today.getDate() < day)) {
age--;
}
console.log("You are " + (age + 1) + " Years old");
var grade = [
[6,'Grade 1'],
[7,'Grade 2'],
[8,'Grade 3'],
[9,'Grade 4'],
[10,'Grade 5'],
[11,'Grade 6'],
];
maxAge=grade.reduce(function(max, grade) {
return Math.max(max, grade[0]);
}, -Infinity);
for (i = 0; i < maxAge; i++){
if(typeof grade[i] !== 'undefined' && grade[i][0]==age){
console.log(grade[i][1]);
}
}
另一种选择可能是:
var dob = '20120810';
var year = Number(dob.substr(0, 4));
var month = Number(dob.substr(4, 2)) - 1;
var day = Number(dob.substr(6, 2));
var today = new Date();
var age = today.getFullYear() - year;
if (today.getMonth() < month || (today.getMonth() == month && today.getDate() < day)) {
age--;
}
//console.log("You are " + (age + 1) + " Years old");
var grade = [
[6,'Grade 1'],
[7,'Grade 2'],
[8,'Grade 3'],
[9,'Grade 4'],
[10,'Grade 5'],
[11,'Grade 6'],
];
let yourGrade = grade.find(e => {
return e[0] == age;
});
console.log('Age: ' + yourGrade[0] + ' and Grade: ' + yourGrade[1]);
添加回答
举报