Function parameter not carried to switch statement in JavaScript - javascript

I've been making a basic game but I've encountered a problem while trying to make a function that would be usable among several occasions by using the switch statement. The output I keep getting when I run the function is the default code block. Here's some sample code:
function battle(boss) {
slaying = true;
while(slaying) {
switch(boss) {
case 'boss1':
console.log('This is' + boss1.name);
break;
case 'boss2':
console.log('This is' + boss2.name);
break;
default:
console.log('No boss');
break;
}
slaying = false;
}
}
function Boss(name) {
this.name = name;
}
var boss1 = new Boss('boss1');
var boss2 = new Boss('boss2');
battle(boss1);

Related

How to go to an a Specific HTML when a word is detected (Java)

Java I made an HTML called hello.html and now I want to use the replace() function in Java to go to the HTML page when the word "Covid" is detected on Google, I tried but it doesn't work for some reason, can you see where I am going wrong, or do I have to change my entire code?
function redirectURL() {
var specWord = getSpecificWord();
switch(specWord)
{
case 'corona':
window.location.replace('hello.html');
break;
case 'covid':
window.location.replace('hello.html');
break;
case 'covid-19':
window.location.replace('hello.html');
break;
default:
return true;
break;
}
return false; // don't let the form submit
}
function getSpecificWord(Element) {
var specificWord = "corona";
return specificWord;
}
The code does not work since you are not calling the redirectURL function.
Append redirectURL() to your code or use this instead:
(function redirectURL() {
var specWord = getSpecificWord();
switch (specWord) {
case 'corona':
window.location.replace('hello.html');
break;
case 'covid':
window.location.replace('hello.html');
break;
case 'covid-19':
window.location.replace('hello.html');
break;
default:
return true;
break;
}
return false; //don't let the form submit
})();
function getSpecificWord(Element) {
var specificWord = 'corona';
return specificWord;
}

Calling a function within a for loop - JavaScirpt

Hi I am trying to call a function within a for loop but It isn't working...This is how my code currently looks like:
bot.on('message', data => {
if (data.type !== 'message' || data.subtype === 'bot_message') {
return;
}
findClassroomMention(data,text);
});
var classrooms =
{
L108: ["lokaal 108","L108","108"],
L208: ["lokaal 208","L208","208"]
};
function findClassroomMention(message) {
var found = false
for(var ClassroomId in classrooms) {
for(var term of classrooms[ClassroomId]) {
if(message.includes(term)) {
found = ClassroomId;
notifyProblemSolver();
break;
}
}
if (found) notifyProblemSolver(); break;
}
return found
};
function notifyProblemSolver(ClassroomId) {
const params = {
icon_emoji: ':smiley:'
}
bot.postMessageToChannel('caris','We have a problem in' + ClassroomId, params);
};
I want the function notifyProblemSolver() to be called in the for loop...But if I run the code it isn't working. Any tips? Thanks in advance!
I think if (found) notifyProblemSolver; break; is the issue. That break will be called regardless of if (found) so for(var ClassroomId in classrooms) { will only run once.
I think you meant
if (found) {
notifyProblemSolver();
break;
}
I've seen some unnecessary semicolons at the end of functions. Also the part:
if (found) notifyProblemSolver; break;
Should be replaced with:
if (found) notifyProblemSolver(); break;
Because you are calling a function here, instead it was an expression.
Let me know if this works.
Full code modification here:
https://jsfiddle.net/terza_terza/ms9xLrzu/3/

Backbone data logic inside view

I am not sure where to perform the action of preparing the data for the template of my view. Currently I have this piece of code.
getTemplateData: function () {
var inventoryStatus = selectedDevice.get("inventoryStatus"),
data = {},
statusName,
inventoryDate;
statusName = getConfigValue("pdp", "statusMap", inventoryStatus);
data.message = getConfigValue("pdp", "statusMessage", statusName);
data.className = "";
data.dataAttribute = null;
data.tooltipValue = null;
data.displayError = false;
var redirectCode = (allDevices.get("thirdPartyRedirectCode") !== null) ? allDevices.get("thirdPartyRedirectCode") : "";
if (redirectCode) {
if (redirectCode === 9999) {
data.buttonDisabled = false;
data.buttonText = "Design Yours";
} else if (redirectCode === 9998) {
data.buttonDisabled = true;
data.buttonText = "Design Yours";
}
return false;
}
switch(inventoryStatus) {
case 1001: //Out of Stock
data.buttonDisabled = true;
data.displayError = true;
break;
case 1002: //Pre Order
data.buttonDisabled = false;
break;
}
return data;
}
This getTemplateData() I call inside my render function of the view. This seems wrong by the looks of it and i am unsure where to place this code.
Should I create different getters in my model or should i leave them inside my main view. Please help.
From what I know the "correct" way of doing this is to put it in the model, and in the view have
getTemplateData: function () {
return this.model.getTemplateData();
}
EDIT
In case of multiple models for a view (which shouldn't happen, without getting into your decisions at the moment) you can have a getTemplateData for each, and call them with something like extend:
getTemplateData: function () {
var data = this.model1.getTemplateData();
data = $.extend(data, this.model2.getTemplateData());
return data;
}
BUT
What you really should do, IMHO, is give each it's own view, where one of them is smaller and intended to be included in the other. (i.e. bigView.$el.append(smallView.el))

Can I implement/put an array on a switch conditional?

I was building my code when came to my mind a bizarre idea, can I implement/put an array inside a switch?
I mean, how can I make the codeHide case work? with this piece of code it don't work.
When I ask to set the command and I put hide() (that is codeHide[0] on the codeHide array) I want to switch take the codeHide case (my if-statement) and return an alert telling me the alertMessage of that particular array element.
If I put hide(background) (that is codeHide[1] on the codeHide array) I want to switch take the codeHide case else (of my if-statement) and return an alert telling me the alertMessage of that particular array element(in the is-statement).
Hope you understand me.
Doing this it don't work and I think it's because the "case codeHide:".
And this is what I've done so far:
var codeHide = ['hide()', 'hide(background)'];
$(".code").on("click", function () {
var codePrompt = prompt("Set the code in the command line."),
alertMessage = "",
consoleMessage = "Used '" + codePrompt + "' command.";
switch (codePrompt) {
case codeHide:
if (codeHide[0]) {
alertMessage = "Hiding elements...";
} else {
alertMessage = "Hiding Background...";
}
break;
default:
alertMessage = consoleMessage = "We are sorry but you entered a WRONG command, try again tho!\ntyped: " + codePrompt;
break;
}
alert(alertMessage);
console.log(consoleMessage);
});
I think you are trying something like
var commands = {
hide: 'hide()',
hideBg: 'hide(background)'
};
var codePrompt = prompt("Set the code in the command line."),
alertMessage;
switch (codePrompt) {
case commands.hide:
alertMessage = "Hiding elements...";
break;
case commands.hideBg:
alertMessage = "Hiding Background...";
break;
default:
alertMessage = "WRONG command";
break;
}
}
However, you can also use
var commands = {
'hide()': "Hiding elements...",
'hide(background)': "Hiding Background..."
};
var codePrompt = prompt("Set the code in the command line.");
var alertMessage = commands[codePrompt] || "WRONG command";
I guess you also want to run some functions:
var commands = {
'hide()': {
text: "Hiding elements...",
funcion: someFunctionToHide
},
'hide(background)': {
text: "Hiding Background...",
funcion: someFunctionToHideBackground
}
};
var codePrompt = prompt("Set the code in the command line."),
command = commands[codePrompt];
if(!command) {
alertMessage = "WRONG command";
} else {
alertMessage = command.text;
command.function();
}
switch operates by comparing the value being switched on to each of the possible cases using the identity operator ===. This means that you can put an array inside a case, and it will work as specified (but certainly not very intuitively for arrays):
var x = [1];
var a = [1];
switch (x) {
case [1]: alert("it's [1]!"); break;
case a: alert("it's a!"); break;
case x: alert("it's x!"); break;
}
This will alert "it's x!", while you might be expecting that either of the preceding two cases would be "good enough" to trigger. But that's just how === works:
[1] === x // false
a === x // true
x === x // true
So while you can technically use an array, in practice it would be very unusual to have a situation where it's actually useful to do so.
Going back to your code, since the values you are interested in are strings it seems that using a simple object as a map would do just fine:
var commands = {
"hide()": {
alert: "Hiding elements...",
console: "Blah blah"
}.
"hide(background)": {
alert: "Hiding background...",
console: "Blah blah"
}.
};
var fallback = {
alert: "Sorry, wrong command",
console: "Sorry, wrong command"
};
which would then allow you to write
var result = commands[input] || fallback;
alert(result.alert);
console.log(result.console);

Changing an image in a switch statement

I have an image in my HTML, but i would like to change the image when an answer is given by the user. For some reason the first function works, but the image doesn't change.. Can someone help me please.
This is my code so far:
window.onload = function () {
'use strict';
var showMessage = function (text) {
var messageCenter = document.getElementById('messageCenter');
messageCenter.innerHTML += "<p>" + text + "</p>\n";
};
var checkName = function (name) {
switch (prompt("What is your name?")) {
case "Leonard":
showMessage("Leonard! How did I not recognize you! Why would you like to get rid of me!");
break;
case "Penny":
showMessage("Penny Penny Penny! You've got so much to learn.");
break;
case "Howard":
showMessage("Howard, the only one without a Ph.D");
break;
case "Raj":
showMessage("Interesting. You're afraid of insects and women. Ladybugs must render you catatonic!");
break;
default:
showMessage("Well, I'm not familiair with you. I don't like to talk to strange people.");
break;
}
};
checkName()
var myImage = document.getElementById('sheldon');
var checkCase = function (img) {
switch (img) {
case "Leonard":
myImage("verbaasd.jpg");
break;
case "Penny":
myImage("les.jpg");
break;
case "Howard":
myImage("howard.jpg");
break;
case "Raj":
myImage("loser.jpg");
break;
default:
myImage("sheldon.jpg");
break;
}
};
checkCase()
};
Your error is in myImage(). You set this variable with a DOM object and call it as a normal function. This gives you an error. You also forgot to store the name and pass it as argument to your checking functions.
Your code should be:
window.onload = function () {
'use strict';
var name = prompt("What is your name?");
var showMessage = function showMessage(text) {
var messageCenter = document.getElementById('messageCenter');
messageCenter.innerHTML += "<p>" + text + "</p>\n";
};
var checkName = function (name) {
switch (name) {
case "Leonard":
showMessage("Leonard! How did I not recognize you! Why would you like to get rid of me!");
break;
case "Penny":
showMessage("Penny Penny Penny! You've got so much to learn.");
break;
case "Howard":
showMessage("Howard, the only one without a Ph.D");
break;
case "Raj":
showMessage("Interesting. You're afraid of insects and women. Ladybugs must render you catatonic!");
break;
default:
showMessage("Well, I'm not familiair with you. I don't like to talk to strange people.");
break;
}
};
checkName(name);
var myImage = function myImage(img) {
var sheldon = document.getElementById('sheldon');
sheldon.innerHTML = '<img src="' + img + '"/>';
};
var checkCase = function (name) {
switch (name) {
case "Leonard":
myImage("verbaasd.jpg");
break;
case "Penny":
myImage("les.jpg");
break;
case "Howard":
myImage("howard.jpg");
break;
case "Raj":
myImage("loser.jpg");
break;
default:
myImage("sheldon.jpg");
break;
}
};
checkCase(name);
};
Now your myImage() is a function which insert a new image inside a container with ID sheldon.
If you don't want to have a container for the image, and instead you want reference directly to the image, can change the myImage() function in:
var myImage = function myImage(img) {
var sheldon = document.getElementById('sheldon');
sheldon.src = img;
};
BTW, I see that you're learning so it's right to start from the basics, but remember that there are cleaner ways to do that.
Hope it's helpful to you.

Categories

Resources