javascript - 不返回用户数组输入
问题描述
输入日期后,我正在尝试返回什么生肖。我有点卡在我的代码的哪一部分没有正确返回值。
我尝试了多个 alert 和 console.log 命令来返回值以及更改不同的方法和代码布局。这是代码。
var start = 1901
var chineseZodiac {
var birthYears {
//Creates Inputs for the date.
var birthDate = parseInt(prompt('Enter the date of birth as an integer, ranging from 1 to 31', '31'));
var birthMonth = parseInt(prompt('Enter the month of birth as an integer, ranging from 1 to 12', '12'));
var birthYear = parseInt(prompt('Enter the year of birth as a 4 digit integer', '2016'));
var birthingTime = new Date(birthDate, birthMonth, birthYear);
//Collecting data on the current time and stores the user inputs
var currentTime = new Date();
currentYear = currentTime.getFullYear();
currentMonth = currentTime.getMonth();
currentDay = currentTime.getDate();
//Declares Array of chineseZodiak
var zodiacSigns = ["Rat", "Ox", "Tiger", "Rabbit", "Dragon", "Snake", "Horse", "Goat", "Monkey", "Rooster", "Dog", "Pig"];
}
resultTest(alert(resultSaving));
//reporting function
}
function resultTest() {
var resultSaving = math.floor(zodiacSigns[(birthYear - start) % 12]);
document.getElementById("myText").innerHTML = resultSaving;
}
console.log(math.floor(zodiacSigns([birthYear - start] % 12)));
解决方案
您的帖子不是有效的 JavaScript,有几处需要更正。
这是一个如何获得预期结果的示例。
/**
* Put the main logic into a function.
*/
function getZodiacSign () {
const start = 1901,
zodiacSigns = ['Rat', 'Ox', 'Tiger', 'Rabbit', 'Dragon', 'Snake', 'Horse', 'Goat', 'Monkey', 'Rooster', 'Dog', 'Pig'];
let birthYear = getUserBirthYear();
const index = (birthYear - start) % 12;
document.getElementById('result').innerHTML =
'Congratulations, you are a <strong>' + zodiacSigns[index] + '</strong> on the Chinese Zodiac';
}
/**
* Use a prompt to get user birth year.
*
* @returns {number}
*/
function getUserBirthYear() {
return parseInt(prompt('Enter the year of birth as a 4 digit integer', '2016'));
}
// Call the function
getZodiacSign();
<div id="result"></div>
您尝试定义变量的方式无效:
var chineseZodiac {
...
}
你在提示用户三遍以后都不会用到的信息,用表单输入收集信息会好很多,而且绝对不要让用户输入你以后不会用到的信息.
// Get rid of these lines
var birthDate = parseInt(prompt('Enter the date of birth as an integer, ranging from 1 to 31', '31'));
var birthMonth = parseInt(prompt('Enter the month of birth as an integer, ranging from 1 to 12', '12'));
var birthingTime = new Date(birthDate, birthMonth, birthYear);
看起来您并没有在任何地方使用当前日期,您也可以摆脱这些行。
//Collecting data on the current time and stores the user inputs
var currentTime = new Date();
currentYear = currentTime.getFullYear();
currentMonth = currentTime.getMonth();
currentDay = currentTime.getDate();
你正在调用math.floor()
一个字符串
math.floor(zodiacSigns[(birthYear - start) % 12]);
相反,使用index
计算得到相应的数组元素。
考虑用表单输入代替提示,用页面中显示的结果代替警报。