javascript logical else if not working [closed] - javascript

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have question about else if
in my case last else not working
var pakeEach = $(".Thide").each(function () {
var cat = $(this).val();
if (cat.indexOf(PCatId) == -1) {
console.log("Pilih tidak ada di your aksess")
} else {
if (cat.indexOf(PCatId) != -1) {
console.log("Show only " + cat);
} else {
console.log("Remove");//why not working last else
}
}
});

Starting with your logic:
if (value == -1) {
...
} else {
if (value != -1) {
...
} else {
...
}
}
you can simplify it to:
if (value == -1) {
...
} else if (value != -1) {
...
} else {
...
}
As you can see, you're saying "if value is -1 then ..., otherwise if value is not -1..." That covers both possible circumstances: value cannot be anything but -1 or not -1 (as discussed by A. Wolff in the comments).
The else can never be hit, since all possible branches have already been covered.
If you want to include the remove logic in one of the other branches (probably the branch where the item was found), you should use something like:
if (value === -1) {
console.log("Pilih tidak ada di your aksess")
} else {
console.log("Show only " + cat);
console.log("Remove!");
}
This is a much more concise way of writing the same thing. Note that the === operator is generally preferred over ==, especially when you know you'll be comparing objects of the same type.
Because you are calling indexOf, the only possible result is the item is in the collection (indexOf(foo) > -1) or not in the collection (indexOf(foo) === -1). There is no third option here, unless you care about where in the collection it is.
For example, to remove the item if it is not the first item present in the collection, you would use:
if (value === -1) {
console.log("Pilih tidak ada di your aksess")
} else if (value === 0) {
console.log("Show only " + cat);
} else {
console.log("Remove!");
}
Because the if conditions only match a small subset of the possible values, the else can actually be hit in this case.

Algorithmically you are saying
if cat.indexOf(PCatId) is equal to -1 then execute the first if block
else execute the second block which is logically treating the case where cat.indexOf(PCatId) is different then -1.
I mean in the first else you can never ever get cat.indexOf(PCatId) == -1 because you are catching it in the first if
here is your answer with some modifications and comments :
var pakeEach = $(".Thide").each(function () {
var cat = $(this).val();
if (cat.indexOf(PCatId) == -1) {
// this part of code is executed if cat.indexOf(PCatId) == -1
console.log("Pilih tidak ada di your aksess")
} else {
// here at this level we can never get cat.indexOf(PCatId) == 1
if (cat.indexOf(PCatId) != -1) {
console.log("Show only " + cat);
}
// this else should be removed !!!! because it is useless
else {
console.log("Remove");//why not working last else
}
}
});

Try this:
var pakeEach = $(".Thide").each(function () {
var cat = $(this).val();
if (cat.indexOf(PCatId) == -1)
{
console.log("Pilih tidak ada di your aksess");
console.log("Remove");
}
else
{
console.log("Show only " + cat);
}
});

What you are trying to do is this:
var pakeEach = $(".Thide").each(function () {
var cat = $(this).val();
if (!cat) {
console.log("Pilih tidak ada di your aksess")
} else if (cat === PCatID) {
console.log("Show only " + cat);
} else {
console.log("Remove");
}
});
First check if cat is empty, then branch according to its value.

Related

Javascript coding quiz not adding up

I'm trying to do a simple quiz where it should sum the correct answers and incorrect answers. The thing is although I put two out of three correct answers, I keep getting the same result for the correct and incorrect array: 0. So there must be something wrong at the end, in the evaluate function. Thanks in advance
var responsesArray= [];
var correct=[];
var incorrect= [];
function question2() {
var firstQuestion = prompt('Does null === 0 ? (Yes or No)')
// why do you need to convert the answer to lowercase?
if (firstQuestion.toLowerCase() === 'yes') {
firstQuestion = true
} else if (firstQuestion.toLowerCase() === 'no') {
firstQuestion = false
} else {
// what if the user writes something other than yes or no?
// they will have to answer the question again
alert("Please answer either Yes or No");
return question2();
}
responsesArray.push(firstQuestion); // add the true or false value to the responses array
}
question2();
function question3() {
var js = prompt('What was the original name for JavaScript: Java, LiveScript, JavaLive, or ScriptyScript?');
js = js.toLowerCase();
switch (js) {
// your own answers
case "livescript":
console.log("Correct!");
break;
case "Java":
console.log("wrong");
break;
case "JavaLive":
console.log("wrong");
break;
case "ScriptyScript":
console.log("wrong");
break;
default:
console.log("Sorry the answer is LiveScript");
}
responsesArray.push(js);
var mine = prompt('What coding language is exclusively related to the back-end: Ruby, JavaScript, HTML?');
mine= mine.toLowerCase();
switch (mine) {
// your own answers
case "ruby":
console.log("Yeah!");
break;
case "html":
console.log("ouuu I'm sorry for you");
break;
case "javascript":
console.log("Yeah but so so");
break;
}
responsesArray.push(mine);
}
question3();
function evaluate(responsesArray)
{
for (var i = 0; i < responsesArray.length; i++)
{
if (responsesArray[i] === true|| "livescript" || "ruby")
{
correct++;
} else{
if (responsesArray[i] !== true|| "livescript" || "ruby") {
incorrect++;
}
}
}
Define an array to store the correct answer and then compare correct and user response and easily can identify whether it is correct or not.
Please check below snippet.
var responsesArray= [];
var correct=0;
var incorrect= 0;
//Correct answer key initialize
var index = 0;
//Initialize array to store correct answer.
var correctAnswers = [];
function question2() {
//Save correct answer.
correctAnswers[index++] = "yes";
var firstQuestion = prompt('Does null === 0 ? (Yes or No)')
// why do you need to convert the answer to lowercase?
if (firstQuestion.toLowerCase() === 'yes') {
console.log("correct");
firstQuestion = 'yes'
} else if (firstQuestion.toLowerCase() === 'no') {
console.log("in-correct");
firstQuestion = 'no'
} else {
// what if the user writes something other than yes or no?
// they will have to answer the question again
alert("Please answer either Yes or No");
return question2();
}
responsesArray.push(firstQuestion); // add the true or false value to the responses array
}
question2();
function question3() {
//Save correct answer.
correctAnswers[index++] = "livescript";
var js = prompt('What was the original name for JavaScript: Java, LiveScript, JavaLive, or ScriptyScript?');
js = js.toLowerCase();
switch (js) {
// your own answers
case "livescript":
console.log("Correct!");
break;
case "Java":
console.log("wrong");
break;
case "JavaLive":
console.log("wrong");
break;
case "ScriptyScript":
console.log("wrong");
break;
default:
console.log("Sorry the answer is LiveScript");
}
responsesArray.push(js);
//Save correct answer.
correctAnswers[index++] = "ruby";
var mine = prompt('What coding language is exclusively related to the back-end: Ruby, JavaScript, HTML?');
mine= mine.toLowerCase();
switch (mine) {
// your own answers
case "ruby":
console.log("Yeah!");
break;
case "html":
console.log("ouuu I'm sorry for you");
break;
case "javascript":
console.log("Yeah but so so");
break;
}
responsesArray.push(mine);
//Call function to evaluate correct or incorrect answer
evaluate(responsesArray,correctAnswers)
}
question3();
function evaluate(responsesArray,correctAnswers)
{
for (var i = 0; i < responsesArray.length; i++)
{
//Match response with correct answer.
if (responsesArray[i] === correctAnswers[i])
{
correct++;
} else{
if (responsesArray[i] !== correctAnswers[i]) {
incorrect++;
}
}
}
alert("Correct : "+correct+" and Incorrect : "+incorrect);
}
The way you test for correct answers is wrong. Instead define an array with the correct answers and verify them as follows:
var correct = incorrect = 0; // better initialise your variables
function evaluate(responsesArray) {
var correctAnswers = [true,"livescript","ruby"];
for (var i = 0; i < responsesArray.length; i++) {
if (responsesArray[i] === correctAnswers[i]) {
correct++;
} else {
incorrect++;
}
}
}
What you had was:
if (responsesArray[i] === true|| "livescript" || "ruby"){
But this means:
if the answer was true, or .... "livescript" is true, or ... "ruby" is true, then
As JavaScript considers strings to be truthy, the if condition would always be true.
Note also that there is no need to do a second if, since the else part is only executed if the first if condition was false, which means you already have filtered for the cases where the answer was wrong.
Finally, your counter variables should be defined before you start incrementing them. It works without this definition, but if one of the two variables is not incremented, it will still be undefined after your call to evaluate. Better always define your variables.

Replacing if else if statements with something more efficient

I'm trying to learn coding by building a simple text game. The end game is going to have 4 rooms. You'll start in room 1, exit west to room 2, exit south to room 3, and finally exit east in room 4. (clockwise).
Anyway, my starting code is from a YouTube tutorial I found that consists of all if / else if statements. I already see that's terribly inefficient. My question is how do I improve this code?
I'm guessing I should make each room and it's contents an object (ie. Room 1 has a sword in it, so the object would contain the location of the room and the sword). I'm also guessing if I have a monster in a room, he'd be his own object.
My problem is if the above is correct (object) - I don't understand how to use the object once I create it. ie. if the user types "take sword" how do I call the object to do that?
If I'm on the complete wrong track, please point me back in the right direction.
Here's the current code for the first room:
$("form").submit(function() {
var input = $("#commandLine").val();
function check() {
check = true;
}
if (input == "help") {
$("#messageHelp").clone().insertBefore("#placeholder").fadeIn(1000);
check();
}
if (input == "take sword" && currentRoom == "nCorridor") {
$("<p>You picked up a sword.</p>").hide().insertBefore("#placeholder").fadeIn(1000);
check();
}
else if (input == "take sword" && currentRoom != "nCorridor") {
$("<p>The sword is not here.</p>").hide().insertBefore("#placeholder").fadeIn(1000);
check();
}
else if (input != "take sword" && input != "help") {
$("<p>I don't understand " + input + ".</p>").hide().insertBefore("#placeholder").fadeIn(1000);
}
$("#commandLine").val("");
});
Ideally, I'd like to eliminate or greatly reduce my need to use if and else if statements for something more efficient.
First let's improve the logic in the if statements to reduce the duplicate conditions, to see how far that gets you:
if (input == "help") {
$("#messageHelp").clone().insertBefore("#placeholder").fadeIn(1000);
check();
} else if (input == "take sword") {
if (currentRoom == "nCorridor") {
$("<p>You picked up a sword.</p>").hide().insertBefore("#placeholder").fadeIn(1000);
check();
} else {
$("<p>The sword is not here.</p>").hide().insertBefore("#placeholder").fadeIn(1000);
check();
}
} else {
$("<p>I don't understand " + input + ".</p>").hide().insertBefore("#placeholder").fadeIn(1000);
}
Another way to determine the action depending on input is using a switch, which may be more useful when you get more options:
switch (input) {
case "help":
$("#messageHelp").clone().insertBefore("#placeholder").fadeIn(1000);
check();
break;
case "take sword":
if (currentRoom == "nCorridor") {
$("<p>You picked up a sword.</p>").hide().insertBefore("#placeholder").fadeIn(1000);
check();
} else {
$("<p>The sword is not here.</p>").hide().insertBefore("#placeholder").fadeIn(1000);
check();
}
break;
default:
$("<p>I don't understand " + input + ".</p>").hide().insertBefore("#placeholder").fadeIn(1000);
}
To go on and using objects for keeping track of items, you could create an object for the sword (with just the location for now):
var sword = {
room: "nCorridor"
};
In the code you could use the object like this:
if (currentRoom == sword.room) {
$("<p>You picked up a sword.</p>").hide().insertBefore("#placeholder").fadeIn(1000);
check();
} else {
$("<p>The sword is not here.</p>").hide().insertBefore("#placeholder").fadeIn(1000);
check();
}
From there you can add more properties and methods to items. The objects might for example have methods that you can use to determine what you can do with them, like that the item apple can be eaten, but the item sword can not.

Use function return as the content for a conditional statement

i'd like to use the return value of a specific function as the condition of an if statement. Is that possible ?
I'm basically building a string inside a function that takes an array (the conditionArray) and concatenates it to a statement.
Then it returns this condition as a string.
After that, i wanted to use this string as the condition of my if-statement.
My current problem looks something like that.
var answer = prompt("Tell me the name of a typical domestic animal");
var conditionArray = new Array("Dog", "Turtle", "Cat", "Mouse")
function getCondition(conditionArray) {
for (i = 0; i < conditionArray.length; i++) {
if (i != conditionArray.length) {
condition += 'answer === ' + conditionArray[i] + ' || ';
} else {
condition += 'answer === ' + conditionArray[i];
}
return condition;
}
}
if (getCondition(conditionArray)) {
alert("That is correct !");
} else {
alert("That is not a domestic animal !");
}
For this type of test use Array.prototype.indexOf, x = arr.indexOf(item)
x === -1 means item is not in arr
Otherwise x is the index of arr that the first occurrence of item is located
var options = ["Dog", "Turtle", "Cat", "Mouse"],
answer = prompt("Tell me the name of a typical domestic animal");
// some transformation of `answer` here, i.e. casing etc
if (options.indexOf(answer) !== -1) {
alert("That is correct !");
} else {
alert("That is not a domestic animal !");
}
The best way to do this kind of test is to use Array.prototype.indexOf. See Paul's answer for more details on how to use it.
--
If you really really want to return a condition, you can use eval() to evaluate the condition string. Keep in mind that eval() is dangerous though. It's usage isn't recommended. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval#Don%27t_use_eval_needlessly!
if (eval(getCondition(conditionArray))) {
alert("That is correct !");
} else {
alert("That is not a domestic animal !");
}

Display error if element in array have 0 value

i have an array in javascript using map function. it collect data from a loop drop down. i just want to ask how to check if array have 0 then display error message. "One of the data not selected"
the array code :
var self_assess_check = $("select[name='self_assess[]'] option:selected").map(function() {
return $(this).text();
}).get();
alert(self_assess_check);
if i alert the array alert(self_assess_check); it produce : 1,0,2,-,-,5,0
how can i make if condition to check if whole array have 0 value then show error message
what i made:
if ((self_assess_check) == "0"){
alert("One of the data not selected");
return false;
}else{
var r=confirm("Make sure all answer is correct. Once Submit it cannot be changed");
if (r==true){
}else{
return false;
}
}
i think my if condition not correct since it will go to else and skip if.tq
Use $.inArray()
if ($.inArray('0', self_assess_check) != -1) {
alert("One of the data not selected");
return false;
} else {
var r = confirm("Make sure all answer is correct. Once Submit it cannot be changed");
if (r == true) {
} else {
return false;
}
}
Note: Array.indexOf() is not used since IE8 might have to be supported.
You can check Array as below code.
function isUndefined(targetO){
return (targetO == 'undefined' || targetO == undefined);
} if(!isUndefined(self_assess_check){ if(self_assess_check.length!=0){alert("Array contain values"); }}
This will work.

If Else Conditionals within Function in JavaScript

I'm having issues with conditionals. I want to return the index where pattern starts in string (or -1 if not found). The search is to be case sensitive if the 3rd parameter is true otherwise it is case insensitive.
Examples
index("abAB12","AB",true) returns 2 but index("abAB12","AB",false) returns 0
index("abAB12","BA",true) returns -1 and index("abAB12","BA",false) returns 1
Any idea how I can accomplish this?
This is my code so far
var s = "abAB12"
var p = "AB"
var cs = true
function index(string, pattern, caseSensitive) {
if (pattern) {
var found = false;
if (caseSensitive = false) {
if (string.indexOf(pattern.) >= 0) {
found = true;
}
return (found);
else {
return ("");
}
} else if (caseSensitive = true) {
if (string.toLowerCase().indexOf(pattern.toLowerCase()) >= 0) {
found = true;
}
return (found);
} else {
return ("");
}
}
}
alert(index(s, p, cs));
Fiddle at http://jsfiddle.net/AfDFb/1/
You have some mistype in your code. On the 15th line you have
}
return (found);
else {
This is not not valid. Change it to
return (found);
}
else {
There is another one.
if (caseSensitive = false) {
= used for assignment. You need to use == in if statements when comparing.
Also on the 13th line, there's an extra . after pattern. Remove it.
if (string.indexOf(pattern.) >= 0) {
Your fiddle example
You can use string.search() with a regular expression to accomplish this in one liner:
function index(input, key, caseMatters) {
return input.search(new RegExp(key, caseMatters ? '' : 'i'));
}
Now you can:
index("abAB12","AB",true); // returns 2
index("abAB12","AB",false); // returns 0
index("abAB12","BA",true); // returns -1
index("abAB12","BA",false); // returns 1
You need to use double equals sign == in your if, else statements.
if(caseSensitive == false)
And
if(caseSensitive == true)
You are assigning value inside if condition instead of comparing it.
Try
if (caseSensitive == false) {
and
if(caseSensitive == true)
You'd better use search :
'abAB12'.search(/AB/); // 2
'abAB12'.search(/AB/i); // 0
'abAB12'.search(/BA/); // -1
'abAB12'.search(/BA/i); // 1
The i flag means "case insensitive" ( insensible à la casse :D ).

Categories