JAVASCRIPT VAR equal if multiple values [duplicate] - javascript

This question already has answers here:
How do I check if an array includes a value in JavaScript?
(60 answers)
Closed 8 years ago.
var position = prompt("position:");
var manager = ["John", "Alex", "Joe"];
var admin = ["Texas", "Jesus", "Rick"];
var tech = ["Nexus", "Thomas", "Fred"]
if (position == manager) {
alert("manager")}
if (position == admin) {
alert("admin")}
if (position == tech) {
alert("tech")
}
else {
alert("Incorrect position")
}
I would like to ask how it is possible to this program work. When I will enter in prompt John I would like to get alert manager when I will enter in prompt Rick I would like to have alert tech etc...
And also if I will enter something what is unknown random value it will get me Incorrect position.
Also I would like to ask if there is way when I will enter in prompt for example jOHN or john it will work. I am total beginner in JS and coding.

You can use indexOf, for example:
if (manager.indexOf(position) !== -1) {
alert("manager");
}

Use .indexOf()
if (manager.indexOf(position) != -1) {
alert("manager")
}

Related

list problem in my javascript todo list exercise [duplicate]

This question already has answers here:
Template literals like 'some ${string}' or "some ${string}" are not working
(7 answers)
Closed last month.
I've checked many times but since I'm new I'm constantly missing something. In the console, my list is does not appear as like this....and my output is like here
Everything is correct, but is there something I don't know about the console?
let input = prompt("What would you like to do?");
const todos= ['list app finish', 'js practice'];
while (input !== 'quit' && input !=="go away aysel"){
if(input === 'list') {
console.log('***********')
for (let num = 0; num< todos.length; i++){
console.log("${num} ${todos[num]}");
}
console.log('*************')
}
input= prompt('What would you like to do')
}
console.log('Good bye')
Template literals work with the backtick char `.
They do not work with string quotes like ' and "
so you need to change the logging to
console.log(`${num} ${todos[num]}`);

How to get split function to work properly? [duplicate]

This question already has answers here:
How do I get the value of text input field using JavaScript?
(16 answers)
Closed 4 months ago.
i am trying to create a function that takes a form input (in this case the name), splits it using the space, and then sends either an error message or an all good message. however, it fails to acknowledge conditions for some reason? it always says that its correct even if i only input a name.
function validateName(){
var nameVal = document.getElementById("yourname");
var nameParts = nameVal.toString().split(" ");
if (nameParts.length<2) {
document.getElementById("yourname").nextSibling.innerHTML = "Please enter your First and Last Name.";}
else {
document.getElementById("yourname").nextSibling.innerHTML = "Thank you for entering your First and Last Name!";
}
}
ive tried changing the code in various ways but there is always some error.
Looks like you forgot to add .value in the first line of your function like this document.getElementById("yourname").value.
function validateName(){
var nameVal = document.getElementById("yourname").value;
var nameParts = nameVal.toString().split(" ");
if (nameParts.length<2) {
document.getElementById("yourname").nextSibling.innerHTML = "Please enter your First and Last Name.";}
else {
document.getElementById("yourname").nextSibling.innerHTML = "Thank you for entering your First and Last Name!";
}
}

Trying to make a language translation app

I am trying to make a translation app that can translate a number between 1-30 from english to its german/french counterpart. I think I am somewhat on the right track, ive made the arrays with all the translations, but the problems I am having is I don't know how to correlate the number the user puts in via a prompt, to one of the values in the array, example:
User is prompted for number between 1-30, user is prompted for language French/German = Translation
This is what I am trying to do. Bellow is what I have so far, feel free to nit pick, but bear in mind I am new to Javascript so there is probably a lot wrong.
function translate() {
if (lang = "French") {
console.log(frenchTranslation);
} else {
console.log(germanTranslation);
}
};
var x=translate
translate(x)
var number=(Number(prompt ("What is your number? Must be between 1-30")));
var lang=(prompt ("What is your language? Must be 'French' or 'German'. Case Sensitive."));
var frenchTranslation = ["Please enter a number between 1-30", "un","deux","trois","quatre","cinq","six","sept","huit","neuf","dix","onze","douze","treize","quatorze","quinze","seize","dix-sept","dix-huit","dix-neuf",
"vingt","vingt et un","vingt-deux","vingt-trois","vingt-quatre","vingt-cinq","vingt-six","vingt-sept","vingt huit","vingt-neuf","trente"];
var germanTranslation = ["Please enter a number between 1-30","Eins","Zwei","Drei","Vier","Fünf","Sechs","Sieben","Acht","Neun","Zehn","Elf","Zwölf","Dreizehn","Vierzehn","Fünfzehn","Sechzehn","Siebzehn","Achtzehn","Neunzehn",
"Zwanzig","Einundzwanzig","Zweiundzwanzig","Dreiundzwanzig","Vierundzwanzig","Fünfundzwanzig","Sechsundzwanzig","Siebenundzwanzig","Achtundzwanzig","Neunundzwanzig","Dreiβig"];
Right, so first of all, you need to add some input validation to know what the user has selected. I recommend storing it somewhere, then you should make sure that it's in the correct range. Just use an if statement to check if the number is >= 0 && <= 30. After that when you're trying to use console.log you need to use array index of the correct number.
Here's my solution, you can improve on it a lot.
var frenchTranslation = ["Please enter a number between 1-30", "un","deux","trois","quatre","cinq","six","sept","huit","neuf","dix","onze","douze","treize","quatorze","quinze","seize","dix-sept","dix-huit","dix-neuf",
"vingt","vingt et un","vingt-deux","vingt-trois","vingt-quatre","vingt-cinq","vingt-six","vingt-sept","vingt huit","vingt-neuf","trente"];
var germanTranslation = ["Please enter a number between 1-30","Eins","Zwei","Drei","Vier","Fünf","Sechs","Sieben","Acht","Neun","Zehn","Elf","Zwölf","Dreizehn","Vierzehn","Fünfzehn","Sechzehn","Siebzehn","Achtzehn","Neunzehn",
"Zwanzig","Einundzwanzig","Zweiundzwanzig","Dreiundzwanzig","Vierundzwanzig","Fünfundzwanzig","Sechsundzwanzig","Siebenundzwanzig","Achtundzwanzig","Neunundzwanzig","Dreiβig"];
function translate()
{
const yournumber = Number(prompt("Enter your number (1-30)"));
console.log(yournumber);
const language = prompt("Choose a language - German or French");
if(yournumber < 1 || yournumber > 30) {
alert("Too hard");
}
else {
if(language === "French") {
console.log(frenchTranslation[yournumber]);
}
if(language === "German") {
console.log(germanTranslation[yournumber]);
}
}
}
translate();

Reverse The Words In A Sentence But Not The Letters [duplicate]

This question already has answers here:
Reversing a string
(4 answers)
Closed 5 years ago.
I want to make a program to reverse the words only, not the letters.
For example...
i love india
... should become...
india love i
Another example...
google is the best website
... should become...
website best the is google
With spaces I have thoroughly researched on it but found just nothing.
My logic is that I should just give you my program that is not working. If you find a small error in my code please give the solution for it and a corrected copy of my program. Also, if you are not too busy, can you please give me the logic in a flow chart.
my logic is here
Thank you for your time.
class Solution {
public String reverseWords(String s) {
if (s == null || s.length() == 0) {
return "";
}
// split to words by space
String[] arr = s.split(" ");
StringBuilder sb = new StringBuilder();
for (int i = arr.length - 1; i >= 0; --i) {
if (!arr[i].equals("")) {
sb.append(arr[i]).append(" ");
}
}
return sb.length() == 0 ? "" : sb.substring(0, sb.length() - 1);
}
}
1.
Store the words of each line in a string array.
2.
Print the elements of the array from the last item to the first.

Better way to create text based game [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
Right, i was uncertain if I should post this as it is a little vague but I really would like some help with this so I will try explain as best as possible.
The Idea:
To create a text based game using Javascript/jQuery, the game will be that of one where a story is being told and you get to pick the options.
My idea was to use a textarea to allow input from the user (select a option) and output text (from the story).
How far have I got?
Well this is what I have created so far.
JavaScript/jQuery:
var current, text, location, option1, option2;
location = ''; // house, car, moon
current = 0;
gameOver = false;
pick = false;
jQuery("textarea").keypress(function (e) {
if (e.which == 13) {
var content = this.value;
var lastLine = content.substr(content.lastIndexOf("\n") + 1);
// Story
if (current == 0 && pick == false) {
option1 = 'Look around';
option2 = 'Check you have arms (Check arms)';
text = 'You open your eyes \n\nOptions: \n' + option1 + '\n' + option2;
pick = true;
} else if (current == 0 && lastLine == 'Check arms' && pick == true) {
text = 'You check your arms, they seem fine';
pick = false;
} else if (current == 0 && lastLine == 'Look around' && pick == true || current == 2 && lastLine == 'Get Out') {
option1 = 'Walk to a nearby house';
option2 = 'Get in a rocket that is next to you (Get in rocket)';
text = 'You do a 360 spin, you see you have limited options \n\nOptions: \n' + option1 + '\n' + option2;
pick = false;
if (current == 2 && lastLine == 'Get Out') {
current = 1;
} else {
current++;
}
}
//House Story
else if (current == 1 && lastLine == 'Walk to house' && pick == false) {
option1 = 'Knock on the front door';
option2 = 'Jump through the front window';
text = 'You walk to the house and see there are no lights on, the building is old and appears to be burnt out\n\nOptions: \n ' + option1 + '\n ' + option2;
pick = false;
current++;
}
// Rocket story
else if (current == 1 && lastLine == 'Get in rocket' && pick == false) {
option1 = 'Get out of the rocket(Get out)';
option2 = 'Hit the biggest button you can find(Hit Button)';
text = 'You hop into the rocket, there are a lot of buttons infront of you\n\nOptions: \n ' + option1 + '\n ' + option2;
pick = false;
current++;
}
$('textarea ').val($('textarea ').val() + '\n\n ' + text + '\n ');
}
});
It works (kinda) but it is getting complicated to code like this. To me its very messy and I have tried to re-write it but I cannot find a way to make this neat/ easier to code.
Have a look at the demo:
Please do take a look at the demo if you wish to try and help me as you will get a good idea what I am trying to achieve.
Demo walk-through:
DEMO HERE
In the textarea click enter to start
Type one of the options to progress in the game (Options: Check arms or Look around)
Type one of the options to progress in the game (Options: Walk to a nearby house or Get in rocket)
End of demo
Note: After typing a option click enter to continue. At the moment all options must be typed exactly as seen (If option has brackets you type that instead)
This is a short demo but you should get the point. I have searched around and cant find/think of a suitable method to code this game.
Get to the point, what's the question?
My questions is: What is a suitable method to code this game?
Suitable: Easy to maintain/read + add new story "parts" etc.
I would go with some kind of strategy pattern. Create i.e. a Game constructor
var Game = new function(strategy) {
this.strategy = strategy;
}
Game.prototyp.playScene = function() {
return this.strategy();
}
Then you can create scenes where you would place your logic
var sceneOne = function() {
console.log('First scene logic here');
}
var sceneTwo = function() {
console.log('Second scene logic here');
}
and finally you can call these logics as follows:
var game;
if(e.which == 13) {
if(condition1) {
game = new Game(sceneOne);
} else {
game = new Game(sceneTwo);
}
game.playScene();
}
fiddle
The biggest issue I see here is that your code is going to grow and grow as your game/story expands. You're actually writing the logic of your game in the code itself.
As an alternative I would suggest splitting out your logic into steps and logic. For example:
var allTiles =
[
{location: 'Forest', description: 'Deep, dark and scary'},
{location: 'Castle', description: 'High, made from stone and very dramatic'},
];
var currentState =
{
equipment: ['Sword', 'Bow', '3 gold coins'];
currentLocationIndex: 0
};
These may of course be in different files so you can add locations to your world.
Next you need your core logic class, this will look a lot like the one you've already got:
jQuery("textarea").keypress(function (e) {
var currentLocation = allTiles[currentState.currentLocationIndex];
printDescription(currentLocation.Description);
// process commands... into pseudo code territory
if(userDoesAction1){
currentLocation.doAction1();
}
}
I've not gone into massive detail here - it will depend very much on the structure of your game. Personally I like the idea of creating an array functions in your location which are things you can do at your location... actually, JS is a very nice language to do this sort of game!
You can use my jQuery terminal. Then you can write core of the game that act on data in JSON object. If you write something like this you will be able to change the data (update or replace) without need to change the code, it's called data driven programming (Eric Raymond write nice chapter in his book about it)
When making games i think that an Object Oriented approach is the best to keep things separated and easy to code and find:
For example you could separate the different rooms in your game in different function structures.
var parentFunction = function(){
var protectedValue = ‘variable’;
var childFunction = function(){
alert(protectedValue);
}
childFunction();
}
var object = new parentFunction();
You initialize the function every time you move to the related ambient, and put the possible actions that the player can take in child-functions.
But i guess the answer would be too big here: you should spend some time before starting to make a scheme of the logic that your game will follow and how you want to separate things (and how they relate to each other).

Categories

Resources