Javascript 将整数与数组匹配以获取值?

Javascript 将整数与数组匹配以获取值?,javascript,Javascript,我不确定它叫什么,但在所有的数学运算完成后,它将返回一个介于0和11之间的值,我需要将该数字与对应于它们位置的zodAnimal和zodAnimalD匹配(因此0将返回rat,以及第一个描述等) 我该怎么做 var birthYear = parseInt(prompt ('Enter your birth year:')); var birthMonth = prompt ('Enter the name of the month of birth:'); var birthDay = par

我不确定它叫什么,但在所有的数学运算完成后,它将返回一个介于0和11之间的值,我需要将该数字与对应于它们位置的zodAnimal和zodAnimalD匹配(因此0将返回rat,以及第一个描述等)

我该怎么做

var birthYear = parseInt(prompt ('Enter your birth year:'));
var birthMonth = prompt ('Enter the name of the month of birth:');
var birthDay = parseInt(prompt ('Enter your day of birth as an integer:'));
var milliDay = 1000*60*60*24; //Milliseconds in a day
monthAbb = 'janfebmaraprmayjunjulaugsepoctnovdec';
chineseZod = 12;
zodCycle = 1924; //Chinese Zodiac Cycle
var zodAnimal = new Array('Rat','Ox','Tiger','Rabbit','Dragon','Snake','Horse','Goat','Monkey','Rooster','Dog','Pig');
var zodAnimalD = new Array('Forthright, tenacious, intense, meticulous, charismatic, sensitive, intellectual, industrious, charming, eloquent, sociable, artistic, and shrewd.  Can be manipulative, vindictive, self-destructive, envious, mendacious, venal, obstinate, critical, over-ambitious, ruthless, intolerant, and scheming.','Dependable, ambitious, calm, methodical, born leader, patient, hardworking, conventional, steady, modest, logical, resolute, and tenacious.  Can be stubborn, dogmatic, hot-tempered, narrow-minded, materialistic, rigid, and demanding.','Unpredictable, rebellious, colorful, powerful, passionate, daring, impulsive, vigorous, stimulating, sincere, affectionate, humanitarian, and generous.  Can be restless, reckless, impatient, quick-tempered, obstinate, selfish, aggressive, and moody.','Gracious, good friend, kind, sensitive, soft-spoken, amiable, elegant, reserved, cautious, artistic, thorough, tender, self-assured, shy, astute, compassionate, lucky, and flexible.  Can be moody, detached, superficial, self-indulgent, opportunistic, and stubborn.','Magnanimous, stately, vigorous, strong, self-assured, proud, noble, direct, dignified, eccentric, intellectual, fiery, passionate, decisive, pioneering, artistic, generous, and loyal.  Can be tactless, arrogant, imperious, tyrannical, demanding, intolerant, dogmatic, violent, impetuous, and brash.','Deep thinker, wise, mystic, graceful, soft-spoken, sensual, creative, prudent, shrewd, elegant, cautious, responsible, calm, strong, constant, and purposeful.  Can be a loner, bad communicator, possessive, hedonistic, self-doubting, distrustful, mendacious, suffocating, and cold.','Cheerful, popular, quick-witted, changeable, earthy, perceptive, talkative, agile, magnetic, intelligent, astute, flexible, and open-minded.  Can be fickle, arrogant, childish, anxious, rude, gullible, and stubborn.','Righteous, sincere, sympathetic, mild-mannered, observant, artistic, intellectual, ingenious, innovative, creative, mothering, peaceful, and generous.  Can be indecisive, over-passive, worrier, pessimistic, sensitive, shy, and weak-willed.','Inventor, motivator, improviser, quick-witted, inquisitive, flexible, innovative, problem solver, self-assured, sociable, artistic, polite, dignified, competitive, objective, and factual.  Can be egotistical, vain, arrogant, selfish, reckless, snobbish, deceptive, manipulative, cunning, jealous, suspicious, and stubborn.','  Acute, neat, meticulous, organized, self-assured, decisive, conservative, critical, perfectionist, alert, zealous, practical, scientific, and responsible.  Can be over zealous and critical, puritanical, egotistical, abrasive, proud, opinionated, and gives into empty bravado.','Honest, intelligent, straightforward, loyal, sense of justice and fair play, attractive, amicable, unpretentious, sociable, open-minded, idealistic, moralistic, practical, affectionate, sensitive, and easy going.  Can be cynical, lazy, cold, judgmental, pessimistic, worrier, stubborn, and quarrelsome.','Honest, gallant, sturdy, sociable, peace-loving, patient, loyal, hard-working, trusting, sincere, calm, understanding, thoughtful, scrupulous, passionate, and intelligent.  Can be naive, over-reliant, self-indulgent, gullible, fatalistic, and materialistic.');

var monthArr = new Array(11);

monthArr [0] = "jan";
monthArr [1] = "feb";
monthArr [2] = "mar";
monthArr [3] = "apr";
monthArr [4] = "may";
monthArr [5] = "jun";
monthArr [6] = "jul";
monthArr [7] = "aug";
monthArr [8] = "sep";
monthArr [9] = "oct";
monthArr [10] = "nov";
monthArr [11] = "dec";

var monthNum = monthAbb.indexOf(birthMonth.slice(0, 3).toLowerCase()) / 3;
alert(monthNum);
var d = new Date (birthYear, monthNum, birthDay);
alert(d);
var dCurrent = new Date();
dCurrent = dCurrent.getTime(); //Grabs the time of the current date in milliseconds.
d = d.getTime(); //Grabs the time of the user-entered date in milliseconds.
var dTotal = dCurrent - d;
alert(dTotal);
dTotal = dTotal / milliDay;
dTotal = Math.floor(dTotal); //7193
alert(dTotal + ' is after division');
dTotal = dTotal / 365.25;
dTotal = Math.floor(dTotal);
alert(dTotal + ' is how old you are!');
dTotal = birthYear - zodCycle;
dTotal = dTotal % chineseZod;
alert(dTotal);

它只是
zodAnimal[dTotal]
zodAnimalD[dTotal]

alert(zodAnimal[dTotal]);
你是说:


console.log(zodAnimal[dTotal]);
console.log(zodAnimalD[dTotal]);

如果要将其写入页面,有两种方法:

  • 您可以只做
    document.write(zodAnimal[dTotal])
    。然而,这是一种非常粗糙的方法,它会删除文档中的所有内容,并写入您想要的内容

  • 另一种方法是创建HTML元素:

  • 现在,您只需在
    中填写
    zodAnimal
    中的数据,如下所示:

    var placeholder = document.getElementById("zodText");
    placeholder.innerHTML = zodAnimal[dTotal];
    

    这里有一个方法我可以做到这一点。一开始我会避免1000*60*60*24这样的事情,因为这是一个常数(一天中的秒数不变,所以不要计算它)

    
    年份:
    月份:
    日期:
    函数val(el){
    返回文档.getElementById(el).value;
    }
    函数计算(){
    风险值数据=[
    [‘老鼠’,‘直率、顽强、热情、细致、有魅力、敏感、聪明、勤奋、迷人、雄辩、社交、艺术和精明。可能具有操纵性、报复性、自我毁灭性、嫉妒性、欺诈性、复仇性、顽固性、批判性、野心勃勃、冷酷无情、不容忍和阴谋’,
    [‘牛’,‘可靠、野心勃勃、冷静、有条不紊、天生的领导者、耐心、勤奋、传统、稳重、谦虚、逻辑、果断和顽强。可能是固执、教条、脾气暴躁、心胸狭窄、唯物主义、僵化和苛求的。’,
    [‘老虎’,‘变幻莫测、叛逆、多姿多彩、强大、热情、大胆、冲动、活力、刺激、真诚、深情、人道主义和慷慨。可能不安、鲁莽、不耐烦、脾气暴躁、固执、自私、好斗和喜怒无常。’,
    ['Rabbit','Gracious,good Friends,善良,敏感,温柔,和蔼可亲,优雅,保守,谨慎,艺术,彻底,温柔,自信,害羞,机敏,富有同情心,幸运,灵活。可能喜怒无常,超然,肤浅,自我放纵,机会主义和固执。],
    [‘龙’,‘宽宏大量、庄严、雄浑、强壮、自信、骄傲、高贵、直率、端庄、古怪、聪明、热情、果断、开拓、艺术、慷慨和忠诚。可能是不得体、傲慢、专横、暴虐、苛求、不容忍、教条、暴力、冲动和鲁莽的。’,
    ['Snake','Deep thinker,wise,mystic,English,soft Speaker,sensual,creative,prudent,精明,优雅,谨慎,负责,冷静,坚强,持续,有目的性。可能是一个孤独的人,沟通能力差,占有欲强,享乐主义,自我怀疑,不信任,虚伪,令人窒息,冷漠的人,
    [“马”,“快活、受欢迎、机智、易变、朴实、敏锐、健谈、敏捷、有吸引力、聪明、机敏、灵活和思想开放。可能变化无常、傲慢、幼稚、焦虑、粗鲁、易受骗和固执。”,
    [“山羊”,“正直、真诚、富有同情心、举止温和、善于观察、艺术、智慧、独创、创新、有创造力、慈母、平和、慷慨。可能犹豫不决、过于被动、焦虑、悲观、敏感、害羞、意志薄弱。”,
    [‘猴子’、‘发明家、激励者、即兴者、机智、好奇、灵活、创新、问题解决者、自信、社交、艺术、礼貌、端庄、竞争、客观和实事求是。可能自私、虚荣、傲慢、自私、鲁莽、势利、欺骗、操纵、狡猾、嫉妒、可疑和固执。],
    [《公鸡》,“敏锐、整洁、细致、有组织、自信、果断、保守、挑剔、完美主义、警觉、热情、务实、科学和负责。可能过于热情和挑剔、清教徒式、利己主义、粗暴、骄傲、固执己见,并虚张声势。”,
    [‘狗’,‘诚实、聪明、直率、忠诚、正义感和公平竞争、有吸引力、友好、谦逊、善于社交、思想开放、理想主义、道德主义、务实、深情、敏感和随和。可能愤世嫉俗、懒惰、冷漠、判断、悲观、担忧、固执和争吵。’,
    [“猪”,“诚实、勇敢、强壮、善于交际、爱好和平、耐心、忠诚、勤奋、信任、真诚、冷静、理解、体贴、谨慎、热情和聪明。可能天真、过度依赖、自我放纵、易受骗、宿命论和唯物论。”
    ];
    var y=parseInt(val(“年份”),10),
    m=parseInt(val(“月”),10),
    d=帕塞因特(val(“日”),10),
    zod_偏移量=(y-1924)%12,
    n=新日期().getTime();
    t=新日期(y,m,d).getTime();
    年龄=数学楼层(数学楼层((n-t)/86400000)/365.25);
    document.getElementById(“result”).innerHTML=“作为“+age\u in_ms+”岁“+数据[zod\u offset][0]+”,您就是“+data[zod\u offset][1]+”

    ”; }
    zodAnimal[0]将返回“rat”。。这就是您要查找的内容吗?我想在页面中写入他们输入到提示中的相应条目。我需要使用document.write,但我认为您所写的内容可能就是我要查找的内容,我只是无法使用console.log。
    <html>
    <body>
    
    <label for='year'>Year:</label><input type='text' id='year' maxlength='4' size='4' />
    <label for='month'>Month:</label><input type='text' id='month' maxlength='2' size='2'/>
    <label for='day'>Day:</label><input type='text' id='day' maxlength='2' size='2' />
    <input type='button' onclick='calc()' value='Calculate' />
    <div id='result'></div>
    
    <script type="text/javascript">
    function val(el) {
        return document.getElementById(el).value;
    }
    
    function calc() {
            var data = [
                ['Rat','Forthright, tenacious, intense, meticulous, charismatic, sensitive, intellectual, industrious, charming, eloquent, sociable, artistic, and shrewd.  Can be manipulative, vindictive, self-destructive, envious, mendacious, venal, obstinate, critical, over-ambitious, ruthless, intolerant, and scheming.'],
                ['Ox','Dependable, ambitious, calm, methodical, born leader, patient, hardworking, conventional, steady, modest, logical, resolute, and tenacious.  Can be stubborn, dogmatic, hot-tempered, narrow-minded, materialistic, rigid, and demanding.'],
                ['Tiger','Unpredictable, rebellious, colorful, powerful, passionate, daring, impulsive, vigorous, stimulating, sincere, affectionate, humanitarian, and generous.  Can be restless, reckless, impatient, quick-tempered, obstinate, selfish, aggressive, and moody.'],
                ['Rabbit','Gracious, good friend, kind, sensitive, soft-spoken, amiable, elegant, reserved, cautious, artistic, thorough, tender, self-assured, shy, astute, compassionate, lucky, and flexible.  Can be moody, detached, superficial, self-indulgent, opportunistic, and stubborn.'],
                ['Dragon','Magnanimous, stately, vigorous, strong, self-assured, proud, noble, direct, dignified, eccentric, intellectual, fiery, passionate, decisive, pioneering, artistic, generous, and loyal.  Can be tactless, arrogant, imperious, tyrannical, demanding, intolerant, dogmatic, violent, impetuous, and brash.'],
                ['Snake','Deep thinker, wise, mystic, graceful, soft-spoken, sensual, creative, prudent, shrewd, elegant, cautious, responsible, calm, strong, constant, and purposeful.  Can be a loner, bad communicator, possessive, hedonistic, self-doubting, distrustful, mendacious, suffocating, and cold.'],
                ['Horse','Cheerful, popular, quick-witted, changeable, earthy, perceptive, talkative, agile, magnetic, intelligent, astute, flexible, and open-minded.  Can be fickle, arrogant, childish, anxious, rude, gullible, and stubborn.'],
                ['Goat','Righteous, sincere, sympathetic, mild-mannered, observant, artistic, intellectual, ingenious, innovative, creative, mothering, peaceful, and generous.  Can be indecisive, over-passive, worrier, pessimistic, sensitive, shy, and weak-willed.'],
                ['Monkey','Inventor, motivator, improviser, quick-witted, inquisitive, flexible, innovative, problem solver, self-assured, sociable, artistic, polite, dignified, competitive, objective, and factual.  Can be egotistical, vain, arrogant, selfish, reckless, snobbish, deceptive, manipulative, cunning, jealous, suspicious, and stubborn.'],
                ['Rooster','Acute, neat, meticulous, organized, self-assured, decisive, conservative, critical, perfectionist, alert, zealous, practical, scientific, and responsible.  Can be over zealous and critical, puritanical, egotistical, abrasive, proud, opinionated, and gives into empty bravado.'],
                ['Dog','Honest, intelligent, straightforward, loyal, sense of justice and fair play, attractive, amicable, unpretentious, sociable, open-minded, idealistic, moralistic, practical, affectionate, sensitive, and easy going.  Can be cynical, lazy, cold, judgmental, pessimistic, worrier, stubborn, and quarrelsome.'],
                ['Pig','Honest, gallant, sturdy, sociable, peace-loving, patient, loyal, hard-working, trusting, sincere, calm, understanding, thoughtful, scrupulous, passionate, and intelligent.  Can be naive, over-reliant, self-indulgent, gullible, fatalistic, and materialistic.']
            ];
            var y = parseInt(val("year"), 10),
                m = parseInt(val("month"), 10),
                d = parseInt(val("day"), 10),
                zod_offset = (y - 1924) % 12,
                n = new Date().getTime();
                t = new Date(y,m,d).getTime();
                age_in_ms = Math.floor(Math.floor( (n-t)/86400000 ) / 365.25);
            document.getElementById("result").innerHTML = "As a " + age_in_ms + " year old " + data[zod_offset][0] + ", you are " + data[zod_offset][1] + "</p>";
    
    }
    </script>
    </body></html>