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.
Related
What can be the JavaScript code for translating app from one language to another for about 30 words, based on "switch"?
Well, it is like any other switch statement aswell, just with 30 cases. It should look something like this:
function translateWord(word) {
let result = '';
switch (word.toLowerCase()) {
case 'apfel': result = 'apple'; break;
case 'kette': result = 'chain'; break;
case 'pflanze': result = 'plant'; break;
}
return result;
}
document.getElementById('result').textContent = translateWord('Apfel');
<h1 id="result"></h1>
the function "translateWord" takes a word, in this case 'Apfel' (german word for apple). That word is passed to the switch statement and transformed to lowercase so it is not case sensitive. After the result is returned and put into the <h1>-Tags on the html page.
Now if you just want to translate 30 words, this might be an option, but common dicionaries have well over six digits of words. So you should look to use a database.
Also JSON might be an option aswell. In my opinion the better way.
const germanToEnglisch = {
word1 = 'Wort1',
word2 = 'Wort2',
word3 = 'Wort3'
};
You can now access the word you want to translate with germanToEnglisch[word1] or with germanToEnglisch.word1, both should work. This requires you to have to word implemented in the object above of course. Hope this helps, i am not sure if i understood your question correctly, as for me it is a bit vague :)
In Adobe Brackets, I am getting warnings from JSLint when writing strict code ['use strict'] that my switch case statement is incorrectly formatted:
eg. Expected 'case' at column #, not column #
If I move everything inside the switch statement back back one "tab" JSLint is happy.
But, Adobe Brackets (And Similar Code Applications) wants to indent the case statements, and even when using Code Beautify it also formats the code to have an indent before the case statement.
When using strict code, is what JSLint is suggesting really the proper way of to format the switch-case statements?
Is there a way to fix/make JSLint in Adobe Brackets so it thinks this indentation is correct? (I would like to stick to not hacking up the JSLint Code)
Why would Editors format the switch-case statement this way if strict code does not want you to do that?
Am I really just doing something wrong here?
Is this just a downside of JSLint and is there a way to avoid using the switch-case statement then altogether thus in the process also making JSLint happy?
Should I really just stop using JSLint altogether? And Switch to something else?
This Code is nested in a for loop:
switch (curButton.button.innerText.toLowerCase()) {
case this.Part1.Button.ButtonText.toLowerCase():
this.Part1.Button.ButtonText = curButton.button.innerText;
this.Part1.Button.Element = curButton.button;
this.Part1.Button.CurrentClass = curButton.button.className;
console.log(smgData.PodCast.Parts.Part1.Button);
break;
case this.Part2.Button.ButtonText.toLowerCase():
this.Part2.Button.ButtonText = curButton.button.innerText;
this.Part2.Button.Element = curButton.button;
this.Part2.Button.CurrentClass = curButton.button.className;
console.log(smgData.PodCast.Parts.Part2.Button);
break;
case this.Part3.Button.ButtonText.toLowerCase():
this.Part3.Button.ButtonText = curButton.button.innerText;
this.Part3.Button.Element = curButton.button;
this.Part2.Button.CurrentClass = curButton.button.className;
console.log(smgData.PodCast.Parts.Part3.Button);
break;
}
Here is some basic code that will reproduce this on https://www.jslint.com/
function abcd() {
var a;
var b;
switch (a) {
case 1:
a=b;
break;
case 2:
b=a;
break;
}
}
This sounds like a problem with JSLint.
It's not exactly what you were asking, but one way to re-formulate the code and avoid switch entirely (and thus the problems JSLint has with switch) is to .find the Part whose ButtonText matches. Then use bracket notation to look up the button on the this:
const currentText = curButton.button.innerText.toLowerCase();
const matchingPart = ['Part1', 'Part2', 'Part3']
.find(part => currentText === this[part].Button.ButtonText.toLowerCase());
if (matchingPart) {
const { button } = this[matchingPart];
button.ButtonText = curButton.button.innerText;
button.Element = curButton.button;
button.CurrentClass = curButton.button.className;
console.log(smgData.PodCast.Parts[matchingPart].Button);
}
If you can control the shape of the this object, it would probably be easier if the Parts were an array, instead of 3 different properties. Then, you could .find over that array, instead of hard-coding the 3 Part properties.
I'd consider the code above to be perfectly fine, but to make it pass all of JSLint's (IMO - opinionated and not-so-good) rules, it'd have to be
const currentText = curButton.button.innerText.toLowerCase();
const props = ["Part1", "Part2", "Part3"];
const matchingPart = props.find(function(part) {
return currentText === this[part].Button.ButtonText.toLowerCase();
});
if (matchingPart) {
const { button } = this[matchingPart];
button.ButtonText = curButton.button.innerText;
button.Element = curButton.button;
button.CurrentClass = curButton.button.className;
console.log(smgData.PodCast.Parts[matchingPart].Button);
}
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;
}
}
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
}
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.");
}