带有 while 循环的 JavaScript 数组
2020-03-27
1265
在此代码中,它应该找到“var dob”的年龄,然后循环遍历数组以找到学生的年级。
有人告诉我,我有正确的代码来查找人的年龄。 我也有正确的数组。我的问题似乎出在我的 while 循环中。
我的 while 循环中的语法有错误。
<script language="javascript" type="text/javascript">
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--;
}
//document.write("You are " + (age + 1) + " Years old"+"<br>");
var grade = [
[6,'Grade 1'],
[7,'Grade 2'],
[8,'Grade 3'],
[9,'Grade 4'],
[10,'Grade 5'],
[11,'Grade 6'],
];
while (var age = 0; age < grade; age++){
document.write(grade[age]);
}
</script>
2个回答
您的一些错误是
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
maswerdna
2020-03-27
如果您正在寻找年龄和年级,这可能是最适合您的解决方案。
请记住,这里的年级是二维数组,您正在将年级的第一个索引元素与年龄进行比较。因此,您需要首先从年级数组的第一个元素中找到最大值。
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]);
Atai Rabby
2020-03-27