我正在做一个学校运动,并且如此接近完成它但却无法弄清楚这一部分。不知道要看什么,要么看到它是非常具体的。我试图做的是显示四个人的年龄,一个未满18岁,这样就会显示出不同的东西,并且成功。 我将展示一张图片以便更好地理解。
我想要的是阻止他们重复,并将不同的年龄分配给四个不同的人。
如果这个人想要显示它们是否超过18,则显示为true,否则显示false。但我希望他们两个同时显示。
这是代码
var iYear = [1995, 1986, 1991, 2002, 1999];
var iAges = [];
var iAdultAges = [];
var lenYear = iYear.length;
var iCurrent = 2017;
for (var i = 0; i < lenYear; i++){
var a = iCurrent - iYear[i];
var iAge = iAges.push(a);
console.log(iAges[0]);
}
for(x = 0; x < iAges.length; x++){ // x = 0 is a starting point
if (iAges[x] < 18){ // x < iAges.length is a ending point, this calculates it as 5
iAdultAges.push(iAges[x]); // x++ says how much we want the value to go up by.
var YoungIndividual = iAges.indexOf(15);
console.log("Person " + YoungIndividual + " is " + iAges[x] + " so they are NOT of age.");
}else if (iAges[x] >= 18){
iAdultAges.push(iAges[x]);
console.log("Mary-Ann is " + iAges[x] + " years old and is of age.");
console.log("Dale is " + iAges[x] + " years old and is of age.");
console.log("Ali is " + iAges[x] + " years old and is of age.");
console.log("Karl is " + iAges[x] + " years old and is of age.");
}
}
function printAdultAge(iYear){
var Ages = [];
var adultAges = [];
var booLean = ["True", "False"];
for (var z = 0; z < lenYear; z++){
var b = iCurrent - iYear[z];
var age = Ages.push(b);
console.log(iAges[0]);
};
for(e = 0; e < Ages.length; e++){ // e = 0 is a starting point
if (Ages[e] < 18){ // e < iAges.length is a ending point, this calculates it as 5
iAdultAges.push(Ages[e]); // e++ says how much we want the value to go up by.
var YoungIndividual = Ages.indexOf(15);
console.log("Person number " + YoungIndividual + " is " + Ages[e] + ". They are too young.");
return booLean[1];
}else if (Ages[e] >= 18){
iAdultAges.push(Ages[e]);
console.log("Mary-Ann is " + Ages[e] + ".");
console.log("Dale is " + Ages[e] + ".");
console.log("Ali is " + Ages[e] + ".");
console.log("Karl is " + Ages[e] + ".");
return booLean[0];
}
}
};
console.log(printAdultAge(iYear));
&#13;
答案 0 :(得分:2)
除非我误解了这个问题,否则看起来你过于复杂了。给出的数据是多年的数组?你是否也给出了这些名字,或者你是否正在制作这些名字?
使用代码中给出的数据,您可以尝试更简单的方法:
var years = [1995, 1986, 1991, 2002, 1999];
var yearsLength = years.length;
var ageThreshold = 18;
var currentYear = new Date().getFullYear();
for (var i = 0; i < yearsLength; i++) {
var personsAge = currentYear - years[i];
var isOfAge = personsAge >= ageThreshold;
console.log('Person ' + (i + 1) + ' is ' + personsAge + ' years old');
console.log(isOfAge);
}
如果给出了数组中的名称,则可以使用相同的索引(i)访问它们,但似乎有4个名称和5年值,因此在尝试读取第5个时会出错。