Let me explain in more detail, I'm making a little sketch for my maths teacher that will calculate the missing sides and angles of a triangle. I have if/else/else if statements but I want an else if statement that will output something like "Check spelling" if none of the other statements are true. Basically, I want something that would do something like this (keep in mind I don't know how to program this yet)
// More code above
else if (side != "hypotenuse and adjacent"; "hypotenuse and opposite"; "opposite and adjacent") {
confirm("Please check spelling.");
}
Can you see what I am trying to do? A previous variable is called side and it prompts the user to input which sides of the triangle they have, so the sketch can work out the angle. What if they have a spelling mistake and it doesn't match any of the parameters I set, how would I make it follow out this block of code if they don't match? I may have just over-complicated things here but if someone could tell me how to do this, it would be greatly appreciated
You can try indexOf:
possibilities = ["hypotenuse and adjacent", "hypotenuse and opposite", "opposite and adjacent"]
// so if side not in that array (the same as not in any of that values)
if (possibilities.indexOf(side) == -1) {}
Are you asking for a default statement if none of the others are matched? Wouldn't that just be an normal else statement?
else{//what you want here}
The simplest way I can think of is to use if, else if and else. By using the else at the end, you won't need to write a huge check for the last line since all the previous.
if (A) { A is true }
else if (B) { Not A, but B }
else if (C) { Not A or B, but C }
else { Not A, B or C }
An much nicer way to do this trick, is to use a switch/case, which is described here.
switch(n) {
case A:
A is true
break;
case B:
B is true
break;
default:
Not A or B
}
However, if you only want the last check for "spell checking", I'd say #zishe has a neat answer to that.
The most simple way to do this is to use jQuery function:
$.inArray(value, array)
which returns either positive index if the string can be found inside of array or -1 otherwise. So the solutions should be something like this:
var myArray = ["hypotenuse and adjacent", "hypotenuse and opposite", "opposite and adjacent"];
// more code above
else if($.inarray(side, myArray) == -1) {
confirm("Please check spelling.");
}
Related
I have a form where one can enter info gain if the want to change anything. The data is taking from the API, this.company is JSON and this.company.name points to the company name.
I have a if else code that does something if the string starts with Be or Pe, first though I want to do something when it doesn't include any of those. But I can't seem to make it with two statements. Can't find any documentation on this what so ever.
Entire code is just two more if else based if it's Be or Pe. They do not affect this code, that works when company name matches any of those. Problem is when company name does not match any of those.
Can anyone help me out?
Tried this:
if (!this.company.name.includes("Be") || !this.company.name.includes("Pe")){
do something}
Also tried
if ((!this.company.name.includes("Be") || !this.company.name.includes("Pe"))){
do something}
Can't get it to work. Last resort is to change the if else and make a last else that will be fall back. But that will cause another problem when input isn't done at all.
Edit.
Seems I wasn't clear on the agenda and full code. I wanted to see if it's possible to have two statements, and use ! infront of them. Here's the full code.
if (this.company){
if (!this.company.name.includes("Be") || !this.company.name.includes("Pe")){
this.category = 0;
some code which will eliminate further questions in the form..
}
else if (this.company.name.includes("Be"){
this.category = 1;
some code ...
}
else if (this.company.name.includes("Pe"){
this.category = 2;
some code...
}
}
You have a minor logic problem here.
I think you wanna go for something like:
if (this.company.name && !(this.company.name.includes("Be") || this.company.name.includes("Pe"))){
That means when the company has a name and this name has no "Be" or "Pe" in the name. Remember if you wanna negate a statement you really have to negate the whole statement and not only parts of it or partwise.
(!A || !B) is not equal to !(A || B)
The first one means When A or B doesnt include "Be" and "Pe" - so far so good - but this statement is also true when only A doesn't include "Be" independent from what B is and it's also true when only B doesn't include "Pe" independent from A. On the upperhand the second one spoken means when A or B doesn't include "Be" and "Pe" - nothing else - You could also write something like (!A && !B) this is the same like !(A || B).
That means you could also go with:
if(!this.company.name.includes("Be") && !this.company.name.includes("Pe"))
A general mathematical overview about this topic would be "Boolean algebra".
Further you said when the name starts with "Be" or "Pe" in your suggestion with "include" these search strings can be anywhere in the String not only in the beginning.
The solution would be the startsWith method for strings:
this.company.name.startsWith("Pe")
Regarding to your update
Correct me if im wrong but I think "be" and "pe" is just the beginning and more categories planned.
Under this conditions i would think of something like this:
if (this.company)
switch(this.company.name.slice(0,2)){
case "Be": this.category = 2;break;
case "Pe": this.category = 1;break;
//possibly more conditions
default : this.category = 0;break; //when company name doesn't start with the cases before
}
In my personal point of view this is a bit more readable. But this depends on the amount of methods and things you wanna call if the conditions are true.
Just add an initial if/else statement to check if there is an input value or not and within the if statement, you can nest your second if/else statement for checking if the company name starts with "Be" or "Pe" using the startsWith() method.
if (this.company.name) { // checks if input has value or not
if (this.company.name.startsWith("Be") || this.company.name.startsWith("Pe")) {
[do something]
} else {
[no company which starts with Be or Pe. Do something else]
}
} else {
[no value was inputted. do something else]
}
Edit:
With regards to your updated question, you can just add a bang ! in the nested if statement and add the other if statements as required like this:
if (this.company.name) { // checks if input has value or not
if (!this.company.name.startsWith("Be") && !this.company.name.startsWith("Pe"))) {
this.category = 0;
} else
if (this.company.name.startsWith("Be")) {
this.category = 1;
} else
if (this.company.name.startsWith("Pe")) {
this.category = 2;
}
} else {
[no value was inputted. do something else]
}
You can use RegExp.test
if(/^(?:Pe|Be)/.test(this.company.name)) {
//starts with Pe or Be
} else {
}
If only care about the case when name does not include any of these
if(/^(?!Pe|Be)/.test(this.company.name)) {
//does not start with Pe or Be
}
Okay, so this may be a repeat, but I personally haven't seen anything on the internet or in Stackoverflow about this.
I am working on a game project and I have been trying to make a text-based game.
In this game, I have a switch statement, for when the user enters a command.
So far I have things for Inventory and Look (Look around the environment), but how do I work with specific things in a switch statement?
For example:
submit = function(input) {
switch(input) {
case "LOOK":
lookaround();
break;
case "LOOK AT" + item:
look();
}
}
It is the LOOK AT line I am having issues with. I do not know how I can make a string work in that format, unless I had a case for every single item individually, example case "LOOK AT ORANGE" or case "LOOK AT TREE".
I hope I am explaining this thoroughly enough. Can anyone give me some advice?
Thanks
EDIT
I think it is important to note that the user is typing the input into an input box, so the value of the input is going to be a string.
If it will help to see the code I have made, please let me know in the comments below.
EDIT
THANKS FOR YOU HELP GUYS!
I used a regular expression (Thanks #red-devil) and a mixture of slicing. It works perfectly now!
Switch works with constants, not expressions like 'LOOK AT' + anything.
You could define an object for map any of your cases to your own functions. Like that:
var looks = {
'lookat-something' : function() {
alert('something');
},
'lookat-other-thing' : function() {
alert('other thing');
},
};
var x = 'lookat-other-thing';
looks[x]();
It much more flexible than using switch in any way.
If I understood you right, you want the user to be able to input LOOK AT and then any item name. The problem here is that you have this ominous item variable that could stand for anything and this is not going to work.
I would suggest one of these two ways:
Going along the lines of your example:
submit = function (input) {
switch (true) {
case input == "LOOK":
alert("Look")
break;
case input.startsWith("LOOK AT"):
alert(input)
break;
}
}
if (typeof String.prototype.startsWith != 'function') {
String.prototype.startsWith = function (str) {
return this.slice(0, str.length) == str;
};
}
And secondly, and this is the method I would recommend, you implement a way to parse any input into a command and parameters. A way to do this is to split the input at every space character and then the first value is the command and the rest would be the parameters. This would require you to use a one word command like LookAt and not LOOK AT.
So something like this:
function submit(input) {
var parts = input.split(" ");
var cmd = parts[0];
var args = parts.slice(1);
switch (cmd) {
case "Look":
lookAround();
break;
case "LookAt":
lookAt(args[0]);
break;
}
}
First time writing Javascript. I just would like know if there is a shorter way of writing this:
<p id="demo"></p>
<script>
function myFunction() {
var letter = document.getElementById("myInput").value;
var text;
if (letter === "5544") {
text = "Abar, Marlon 1,800";
} else if (letter === "5545") {
text = "Pia, Darla 1,800";
} else if (letter === "5546") {
text = "Salazar, Alex 1,500";
//etc...
} else {
text = "Incorrect Account Number";
}
document.getElementById("demo").innerHTML = text;
}
</script>
Tried map but I couldn't get it to work.
There isn't really a shorter way to write an if statement in that way (which I will assume is what you're asking). However, there could be a few different ways to write this depending on how many things you want to check.
Use a Switch statement
There is a cleaner way when dealing with multiple cases that letter could be.
This would be a switch statement and it would look like this:
var text;
switch (letter) {
case "5544":
text = "Abar, Marlon 1,800";
break;
case "5545":
text = "Pia, Darla 1,800";
break;
// more cases
default:
text = "Incorrect Account Number";
break;
}
This reads a little better than an if else statement in some cases. The default keyword here acts as your else clause in an if else statement. The case acts as your different if statements if you will.
Essentially, the switch statement above will fall through each of the cases it defines until it finds a case that matches letter (such as "5544"). If none matches, it hits the default case. The break keyword at the end of each case stops things from falling through to the next defined case once a match is found.
This method could get cumbersome with more than 6 or 7 cases.
Create an object and look up the value
Now, a shorter way to get the value you want could be to define an object and get the value based on what has been entered like so:
var letter = document.getElementById('selector').value;
var obj = {
'5544': 'Abar, Marlon 1,800'
};
if (letter in obj) {
// do something if found
}
else {
// do something if not found
}
This could be an easy way to get a value if you have many values to check.
Other thoughts
As a side note to all of this, there are short hand if statements called ternary statements which you can find here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator ... However, I would not recommend nesting these as it becomes very complicated and not very readable.
Conclusion
So, to reiterate the answer to your question: No, there isn't really a shorter way to write an if else statement with many values. You can use a switch statement to make it cleaner. Use the object lookup method if you have many values you would like to check.
JavaScript has object (map) literals. Use them for terse code. In your final application you'll get the data for the map from someplace else and not code it directly into your website, but if you did, it would look like this:
document.getElementById( "demo" ).innerHTML = {
"5544" : "Abar, Marlon 1,800",
"5445" : "Pia, Darla 1,800",
...
}[ document.getElementById( "myInput" ).value ];
you can use switch for a long if - else -if ladder:
switch(expression) {
case n:
code block
break;
case n:
code block
break;
default:
default code block
}
This is how it works:
1)The switch expression is evaluated once.
2)The value of the expression is compared with the values of each case.
3)If there is a match, the associated block of code is executed.
if you need basic tutorials in java script then you should try w3 schools.
I have the following situation:
var answer = 'three';
var isClosed = true;
var condition = "answer != null && !isClosed";
The condition is a literal string and it's dynamically set by the user. Once they set the condition, I need to evaluate it inside an IF/ELSE sentence:
if(condition)
//Do something
else
//Do something
Can I do that without using "eval()"? How? I want to avoid it:
if(eval(condition))
...
NOTE: This is a simple example, the real situation is a bit complex with dynamic conditions :)
If you want to evade eval at all cost (as it can be really dangerous for the security reasons), you basically need a rules engine adapted to your dsl that you get from the database.
I googled this one and it seems prety decent C2FO , didn't actually tried it, but now you know where to start.
A bit confused..
But if the answer and isClosed set by the user.. then just something like this will suffice..
answer = null
isClosed = false // the default value for isClosed
if(answer != null && !isClosed){
//Do something
}
else{
//Do something
}
Here is a snippet of JavaScript code from a tutorial I was working with. I don’t understand why it doesn’t end with a final else clause; I thought that was a rule.
var curScene = 0;
function changeScene(decision) {
var message = "";
if(curScene == 1) {
message = " welcome";
} else if (curScene == 2) {
message = " this is scene two";
} else if (curScene == 3) {
message = " this is scene three";
}
document.getElementById("sceneimg").src = "scene" + curScene + ".png";
if(message != ""){
alert(message);
}
}
I thought it was always supposed to end with an "else"?
The else block is optional. You can have if without else.
For the same reason as why you can have just a single if:
if( /*condition*/ ) {
//some code
}
//other stuff
Consider 3 Scenario
Scenario 1: Boolean condition
if (condition) {}
else {}
Specifying a condition as else if would be redundant, and it's really obvious to the reader what the code does. There is no argument for using else if in this case.
Scenario 2: Infinite states
Here we are interested in testing for conditions A and B (and so on), and we may or may not be interested in what happens if none of them holds:
if (conditionA) {}
else if (conditionB) {}
else {} // this might be missing as it is in your case
The important point here is that there isn't a finite number of mutually-exclusive states, for example: conditionA might be num % 2 == 0 and conditionB might be num % 3 == 0.
I think it's natural and desirable to use a reasonable amount of branches here; if the branches become too many this might be an indication that some judicious use of OO design would result in great maintainability improvements.
Scenario 3: Finite states
This is the middle ground between the first two cases: the number of states is finite but more than two. Testing for the values of an enum-like type is the archetypal example:
if (var == CONSTANT_FOO) {}
else if (var == CONSTANT_BAR) {} // either this,
else {} // or this might be missing
In such cases using a switch is probably better because it immediately communicates to the reader that the number of states is finite and gives a strong hint as to where a list of all possible states might be found (in this example, constants starting with CONSTANT_). My personal criteria is the number of states I 'm testing against: if it's only one (no else if) I 'll use an if; otherwise, a switch. In any case, I won't write an else if in this scenario.
Adding else as an empty catch-errors block
This is directly related to scenario #2 above. Unless the possible states are finite and known at compile time, you can't say that "in any other case" means that an error occurred. Seeing as in scenario #2 a switch would feel more natural, I feel that using else this way has a bad code smell.
Use a switch with a default branch instead. It will communicate your intent much more clearly:
switch(direction) {
case 'up': break;
case 'down': break;
default: // put error handling here if you want
}
This might be a bit more verbose, but it's clear to the reader how the code is expected to function. In my opinion, an empty else block would look unnatural and puzzling here.
It doesn't have to, for the same reason an if on its own doesn't require an else.
Usually it's a good idea to have one, as a sort of "catch-all" situation, but the above code could be written as:
switch(curScene) {
case 1: message = " welcome"; break;
case 2: message = " this is scene two"; break;
case 3: message = " this is scene three"; break;
}
In the above code, I could also add:
default: message = " invalid curScene value"; break;
But it's completely optional to do so. It depends on how reliable the curScene variable is whether or not I personally would add it in.
Not having an else clause is fine syntactically. MDN Documentation Basically the second if becomes the body of the else, see the section on "how it would look like if the nesting were properly indented".
As to whether it's bad practice I think that depends on intent. By not explicitly defining the final else clause, you might end up with a bug where a condition you didn't cover comes through. Consider this:
if(myVariable > 0) {
doSomething();
} else if(myVariable < 0) {
doSomethingElse();
}
Nothing happens if myVariable is 0. It would be hard to see if you were just glancing through the code. I would say if you run into this pattern it would be a code smell, something might be wrong, but it could be fine.
The same logic could always be expressed with nested if statements. I would go with whatever is more readable.
else is a default case for the if statement.
If there is no else then if none of the conditions in the if or else if cases are met than the if statment will do nothing.
Usually it is good practice to have a default case but there are a lot of times where it is not necessary and thus excluded from the code.
In this case, if the curScene was anything other than 1, 2, 3 then the else statment would be used, but since there is no processing to be done on other cases the coder has not included an else.
yes, always have a else is VERY GOOD habit(when using with if-elseif). sometimes people might even write this:
if(curScene == 1) {
message =" welcome";
else if (curScene == 2) {
message = " this is scene two";
}
else if (curScene == 3) {
message = " this is scene three";
} else {
// empty.
}
to tell people there is indeed nothing to do in the else.
change the if condition for answer validation if(answer==100) to if(answer===100)
it is working fine now...