简体   繁体   English

如果使用Java语句嵌套

[英]Nesting If Else Statements in Javascript

I'm beginning to create a web app where a user will select their age, gender and a few other things, which will then return a piece of information specific to their answers. 我开始创建一个Web应用程序,用户可以在其中选择自己的年龄,性别和其他一些内容,然后将返回一条特定于其答案的信息。

I've always neglected learning Javascript properly, so it's something of a learning experience. 我一直忽略正确学习Java脚本,因此这是一种学习体验。 The most obvious way to me seemed to be with if/else statements. 对我来说,最明显的方法似乎是使用if / else语句。 However, I am wary that this would lead to very messy code, so I'm wondering whether I'm way off the mark in pursuing this project with just plain Javascript or if else statements. 但是,我很警惕,这会导致代码非常混乱,所以我想知道我是否仅使用纯Javascript或其他语句来追求这个项目是否偏离了正常。

I've began the task with JS, but it's tripping up somewhere. 我已经开始使用JS进行这项任务,但是它在某个地方发生了故障。 It correctly selects the gender, then the age, but when I try to display information based on both selections, it gets it incorrect. 它正确地选择了性别,然后选择了年龄,但是当我尝试根据这两个选择显示信息时,会得到不正确的信息。

 /* If you're feeling fancy you can add interactivity to your site with Javascript */ // prints "hi" in the browser's dev tools console console.log('hi'); function gender() { var userGender = document.getElementById("genderInput").value; console.log('Gender selected as ' + userGender); } function age() { var userAge = document.getElementById("ageInput").value; console.log('Age selected as ' + userAge); } function summary() { if (userGender = 'Male') { if (userAge = 'u35') { console.log('The user is ' + userGender + 'and ' + userAge + ' years old'); } else if (userAge = '36-45') { console.log('The user is ' + userGender + 'and ' + userAge + ' years old'); } else if (userAge = '46-55') { console.log('The user is ' + userGender + 'and ' + userAge + ' years old'); } else if (userAge = '56-65') { console.log('The user is ' + userGender + 'and ' + userAge + ' years old'); } else if (userAge = 'o65') { console.log('The user is ' + userGender + 'and ' + userAge + ' years old'); } } else if (userGender = 'Female') { if (userAge = 'u35') { console.log('The user is ' + userGender + 'and ' + userAge + ' years old'); } else if (userAge = '36-45') { console.log('The user is ' + userGender + 'and ' + userAge + ' years old'); } else if (userAge = '46-55') { console.log('The user is ' + userGender + 'and ' + userAge + ' years old'); } else if (userAge = '56-65') { console.log('The user is ' + userGender + 'and ' + userAge + ' years old'); } else if (userAge = 'o65') { console.log('The user is ' + userGender + 'and ' + userAge + ' years old'); } } else { console.log('nothing selected'); } } 
 <!DOCTYPE html> <html lang="en"> <head> <title>Hello!</title> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- import the webpage's stylesheet --> <link rel="stylesheet" href="/style.css"> <!-- import the webpage's javascript file --> <script src="/script.js" defer></script> </head> <body> <h1>Hi there!</h1> <h3> Gender </h3> <form id="genderApp" onsubmit="return false;"> <select id="genderInput" name="genderSelect"> <option value="Male">Male</option> <option value="Female">Female</option> </select> <input type="submit" onclick="gender()"> </form> <h3> Age </h3> <form id="ageApp" onsubmit="return false;"> <select id="ageInput" name="ageSelect"> <option value="u35">Under 35</option> <option value="36-45">36-45</option> <option value="46-55">46-55</option> <option value="56-65">56-65</option> <option value="o65">Over 65</option> </select> <input type="submit" onclick="age()"> </form> <button onclick="summary()"> Summary </button> <!-- include the Glitch button to show what the webpage is about and to make it easier for folks to view source and remix --> <div class="glitchButton" style="position:fixed;top:20px;right:20px;"></div> <script src="https://button.glitch.me/button.js"></script> </body> </html> 

Appreciate any help, whether it's pointing out the error in this attempt or calling me a fool for attempting this with this method! 感谢任何帮助,无论是指出此尝试中的错误还是称呼我为使用此方法进行尝试的傻瓜!

Why you code isn't working is addressed in the comments, you are using = instead of === . 注释中说明了为什么您的代码不起作用的原因,您使用的是=而不是=== One is assignment operator the other performs equality checks. 一个是赋值运算符,另一个是相等性检查。

I'm wondering whether I'm way off the mark in pursuing this project with just plain Javascript or if else statements 我想知道我是否仅使用简单的Javascript来追求这个项目还是其他陈述

You can use an array of objects to declare responses and their constraints instead of if/else blocks. 您可以使用对象数组来声明响应及其约束,而不是if/else块。

 const responses = [ { age: { min: 5, max: 12 }, gender: 'male', func: function() { console.log('is a male between 5 - 12') } }, { age: { min: 60, max: 65 }, gender: 'female', func: function() { console.log('is a female between 60 - 65') } } ] const main = (age, gender) => { // find a response that matches all constraints const response = responses.find(response => { return response.gender === gender && response.age.min <= age && response.age.max >= age }) if (!response) { throw 'No response found for this age range/gender' } response.func() } main(8, 'male') main(60, 'female') 

This can be made even more DRY ; 这可以做得更 ; The response func message can be computed by the gender and age.min / age.max props but that's besides the question. 响应func消息可以通过genderage.min / age.max道具来计算,但这不是问题。

Just create a single function and on click of summary get the gender and the age range 只需创建一个函数,然后单击摘要即可获取性别和年龄范围

 console.log('hi'); function summary() { var userGender = document.getElementById("genderInput").value; var userAge = document.getElementById("ageInput").value; console.log(`The user is ${userGender} and ${userAge} years old`) } 
 <h1>Hi there!</h1> <h3> Gender </h3> <form id="genderApp" onsubmit="return false;"> <select id="genderInput" name="genderSelect"> <option value="Male">Male</option> <option value="Female">Female</option> </select> <input type="submit" onclick="gender()"> </form> <h3> Age </h3> <form id="ageApp" onsubmit="return false;"> <select id="ageInput" name="ageSelect"> <option value="u35">Under 35</option> <option value="36-45">36-45</option> <option value="46-55">46-55</option> <option value="56-65">56-65</option> <option value="o65">Over 65</option> </select> <input type="submit" onclick="age()"> </form> <button onclick="summary()"> Summary </button> <!-- include the Glitch button to show what the webpage is about and to make it easier for folks to view source and remix --> <div class="glitchButton" style="position:fixed;top:20px;right:20px;"></div> 

You are making two mistakes here: 您在这里犯了两个错误:

  • First you using assignment operator = for if stataments. 首先,对if语句使用赋值运算符= You should comparison operator == or === but in this case you don't need to do that because all the block have same console.log() 您应该比较运算符=====但是在这种情况下,您不需要这样做,因为所有块都具有相同的console.log()
  • The variable userGender and userAge should be declared in global scope 变量userGenderuserAge应该在全局范围内声明

 /* If you're feeling fancy you can add interactivity to your site with Javascript */ // prints "hi" in the browser's dev tools console console.log('hi'); var userGender; var userAge; function gender() { userGender = document.getElementById("genderInput").value; console.log('Gender selected as ' + userGender); } function age() { userAge = document.getElementById("ageInput").value; console.log('Age selected as ' + userAge); } function summary() { console.log(`The user is ${userGender} and ${userAge} years old`); } 
 <!DOCTYPE html> <html lang="en"> <head> <title>Hello!</title> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- import the webpage's stylesheet --> <link rel="stylesheet" href="/style.css"> <!-- import the webpage's javascript file --> <script src="/script.js" defer></script> </head> <body> <h1>Hi there!</h1> <h3> Gender </h3> <form id="genderApp" onsubmit="return false;"> <select id="genderInput" name="genderSelect"> <option value="Male">Male</option> <option value="Female">Female</option> </select> <input type="submit" onclick="gender()"> </form> <h3> Age </h3> <form id="ageApp" onsubmit="return false;"> <select id="ageInput" name="ageSelect"> <option value="u35">Under 35</option> <option value="36-45">36-45</option> <option value="46-55">46-55</option> <option value="56-65">56-65</option> <option value="o65">Over 65</option> </select> <input type="submit" onclick="age()"> </form> <button onclick="summary()"> Summary </button> <!-- include the Glitch button to show what the webpage is about and to make it easier for folks to view source and remix --> <div class="glitchButton" style="position:fixed;top:20px;right:20px;"></div> <script src="https://button.glitch.me/button.js"></script> </body> </html> 

I just corrected the mistakes without improving the code. 我只是纠正了错误,而没有改进代码。

== should be used for comparing values and = for assignment ==应该用于比较值,而=则用于赋值

And variable should be global if you want to access it globally else get those variables initialized in function itself. 如果要全局访问变量,则变量应为全局变量,否则应在函数本身中初始化这些变量。

 /* If you're feeling fancy you can add interactivity to your site with Javascript */ // prints "hi" in the browser's dev tools console console.log('hi'); function gender() { var userGender = document.getElementById("genderInput").value; console.log('Gender selected as ' + userGender); } function age() { var userAge = document.getElementById("ageInput").value; console.log('Age selected as ' + userAge); } function summary() { var userGender = document.getElementById("genderInput").value; var userAge = document.getElementById("ageInput").value; if (userGender == 'Male') { if (userAge == 'u35') { console.log('The user is ' + userGender + 'and ' + userAge + ' years old'); } else if (userAge == '36-45') { console.log('The user is ' + userGender + 'and ' + userAge + ' years old'); } else if (userAge == '46-55') { console.log('The user is ' + userGender + 'and ' + userAge + ' years old'); } else if (userAge == '56-65') { console.log('The user is ' + userGender + 'and ' + userAge + ' years old'); } else if (userAge == 'o65') { console.log('The user is ' + userGender + 'and ' + userAge + ' years old'); } } else if (userGender == 'Female') { if (userAge == 'u35') { console.log('The user is ' + userGender + 'and ' + userAge + ' years old'); } else if (userAge == '36-45') { console.log('The user is ' + userGender + 'and ' + userAge + ' years old'); } else if (userAge == '46-55') { console.log('The user is ' + userGender + 'and ' + userAge + ' years old'); } else if (userAge == '56-65') { console.log('The user is ' + userGender + 'and ' + userAge + ' years old'); } else if (userAge == 'o65') { console.log('The user is ' + userGender + 'and ' + userAge + ' years old'); } } else { console.log('nothing selected'); } } 
 <!DOCTYPE html> <html lang="en"> <head> <title>Hello!</title> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- import the webpage's stylesheet --> <link rel="stylesheet" href="/style.css"> <!-- import the webpage's javascript file --> <script src="/script.js" defer></script> </head> <body> <h1>Hi there!</h1> <h3> Gender </h3> <form id="genderApp" onsubmit="return false;"> <select id="genderInput" name="genderSelect"> <option value="Male">Male</option> <option value="Female">Female</option> </select> <input type="submit" onclick="gender()"> </form> <h3> Age </h3> <form id="ageApp" onsubmit="return false;"> <select id="ageInput" name="ageSelect"> <option value="u35">Under 35</option> <option value="36-45">36-45</option> <option value="46-55">46-55</option> <option value="56-65">56-65</option> <option value="o65">Over 65</option> </select> <input type="submit" onclick="age()"> </form> <button onclick="summary()"> Summary </button> <!-- include the Glitch button to show what the webpage is about and to make it easier for folks to view source and remix --> <div class="glitchButton" style="position:fixed;top:20px;right:20px;"></div> <script src="https://button.glitch.me/button.js"></script> </body> </html> 

Other answers have told you your mistakes. 其他答案已告诉您您的错误。

Here is my version intended to educate on better practices 这是我的版本,旨在教育更好的做法

  • using unobtrusive event listeners 使用不引人注目的事件监听器
  • using an object to match proper text to values 使用对象将适当的文本与值匹配

 var ages = { u35: "under 35", "36-45": "between 36 and 35", "46-55": "between 46 and 55", "56-65": "between 56 and 65", "o65": "over 65" } window.addEventListener("load", function() { document.getElementById("genderInput").addEventListener("change", function() { var userGender = this.value; console.log('Gender selected as ' + userGender); }); document.getElementById("ageInput").addEventListener("change", function() { var userAge = this.value; console.log('Age selected as ' + userAge); }); document.getElementById("summary").addEventListener("click", function() { var userGender = document.getElementById("genderInput").value; var userAge = document.getElementById("ageInput").value; if (!userGender && !userAge) { console.log('nothing selected'); return; } var text = []; if (userGender) text.push(userGender); if (userAge) text.push(ages[userAge] + ' years old'); console.log('The user is ' + text.join(" and ")); }) }); 
 <h1>Hi there!</h1> <form> <h3>Gender</h3> <select id="genderInput" name="genderSelect"> <option value="">Please select</option> <option value="Male">Male</option> <option value="Female">Female</option> <option value="Other">Other</option> </select> <h3>Age</h3> <select id="ageInput" name="ageSelect"> <option value="">Please select</option> <option value="u35">Under 35</option> <option value="36-45">36-45</option> <option value="46-55">46-55</option> <option value="56-65">56-65</option> <option value="o65">Over 65</option> </select> <button id="summary" type="button">Summary</button> </form> 

Using es6 template strings we can build a smart console log based on criteria passed to the handleUser method 使用es6模板字符串,我们可以基于传递给handleUser方法的条件来构建智能控制台日志

 const handleUser = filter => { const age = filter === 'gender' ? null : document.querySelector('#ageInput').value const gender = filter === 'age' ? null : document.querySelector('#genderInput').value if (!gender && !age) return alert('please complete the form') // build log frorm age and gender data console.log(`User is ${!!gender ? gender : ''}${!!gender && !!age ? ' and ' : ''}${!!age ? `aged ${age}` : ''}`) // Use switch to handle your age ranges (more readable imho than if-else etc) // assumig eventually you are going to want to add more logic based on age... switch (age) { case 'u35': break; case '36-45': break; case '46-55': break; case '56-65': break; case 'o65': break; default: break; } } 
 <h1>Hi there!</h1> <h3> Gender </h3> <form id="genderApp" onsubmit="return false;"> <select id="genderInput" name="genderSelect"> <option></option> <option value="Male">Male</option> <option value="Female">Female</option> </select> <input type="submit" onclick="handleUser('gender')"> </form> <h3> Age </h3> <form id="ageApp" onsubmit="return false;"> <select id="ageInput" name="ageSelect"> <option></option> <option value="u35">Under 35</option> <option value="36-45">36-45</option> <option value="46-55">46-55</option> <option value="56-65">56-65</option> <option value="o65">Over 65</option> </select> <input type="submit" onclick="handleUser('age')"> </form> <button onclick="handleUser()"> Summary </button> </br> </br> </br> </br> </br> </br> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM