If-causes with boolean in javascript (Beginners) - javascript

Is there a possibility to write this "If" more efficient?
if((text.val(“Hello“) == false)&& (text.val(“This“) == true)&&(text.val(“Is“) == false)&&(text).val(“Me“) == false))
{
text = "This"
}
This “if“ should check, whether a value is set true or not. It should display only the “true“ one. If I make it in this way, I have to make a lot of If’s in order to have all possibilities. Is there a way to make it more efficient and better? In database all values are boolean.

To test for one of multiple conditions you could use:
var txt = text.val();
switch(txt){
case "Hello":
case "This":
case "Is":
case "Me":
case "Whatever Else":
text.val("This");
break;
}
This will allow you to test very simply for multiple conditions and respond accordingly. In this case it will return true is any of these conditions are true. To require all would be:
if (txt=="This" && txt=="Hello" && txt=="Is" && txt=="Me"){...}
This is the only way to test that all conditions are true, unless you want to use arrays and a true-false marker.

I think you might be confused as to how .val() works. If the parameter is left empty, it returns the value. If it has a parameter, it sets the value. (jQuery API Documentation) If I read your if statement correctly, it will only execute if the value of the text is equal to "This". This could be simplified by the following:
if(text.val() == “This“) {
text.val("This");
}
In case you wanted your statement rewritten, here is how it might look:
if((text.val() != “Hello“) && (text.val() == “This“) && (text.val() != “Is“) && (text).val() != “Me“))
{
text.val("This");
}
I would also recommend looking through the documentation in link above and even looking through W3Schools.com

This is an efficient way without jQuery or other library:
var text = "Hello This Is Me";
var textSplit = text.split(' ');
var count = textSplit.length;
for(i=0;i<=count;i++){
if(textSplit[i] == 'This'){
text = 'This';
alert(text);
break;
}
}

Related

Appropriate way to check if 4 strings are duplicated in JS [duplicate]

Working in Javascript, I am trying to see if 5 different variables all contain the same value at a given time. The value could be 1 of 6 things, but I need to see if they are all the same regardless of which value it is. I have tried this:
if (die1 == die2 & die1 == die3 & die1 == die4 & die1 == die5) {
yahtzeeQualify == true;
}
and this:
if (die1 == die2 == die3 == die4 == die5) {
yahtzeeQualify == true;
}
Are either of these valid? If so, there is probably an error in my code somewhere else...if not, I'd really appreciate some help. I also have these variables in an array called dieArray as follows:
var dieArray = [die1, die2, die3, die4, die5];
It would be cool to learn a way to do this via the array, but if that isn't logical then so be it. I'll keep trying to think of a way on my own, but up until now I've been stuck...
Are either of these valid?
They are "valid" (as in this is executable code) but they don't perform the computation you want. You want to use a logical AND (&&) not a bitwise AND.
The second one is just wrong. You run into type coercion issues and end up comparing die1 to either true or false.
It would be cool to learn a way to do this via the array
You can use Array#every and compare whether each element is equal to the first one:
if (dieArray.every(function(v) { return v === dieArray[0]; }))
// arrow functions make this nicer:
// if (dieArray.every(v => v === dieArray[0]))
Solution with the Array.reduce:
var values = [die1, die2, die3, die4, die5];
var yahtzeeQualify = values.reduce(function(memo, element) {
return element === values[0];
});
The 1st one is what you want, but it's messed up. You want && not &
The 2nd one is logically wrong.
To do it with an array
yahtzeeQualify = dieArray.every(function(n){ return n === dieArray[0] })

Javascript - Waiting for user input (callbacks)

I've been looking at other questions trying to get my head around callbacks but I just can't make sense of it enough to use in my context. I'm writing a text based game which uses purely text input. When needed, I want the game to ask a question with a varying amount of answers and then wait until a valid response is given. Below is an example that doesn't work but explains what I'm trying to do. Can anyone provide me with any guidance? Thanks.
//main code
pEQUIP = ["foo", "foo", "foo"];
exItem = "ball";
function prompt(numPrompts, callback) {
//waits until user types a number <= numPrompts and presses enter, then returns the valid result entered
}
$('#gametext').append("<p>" + "What slot would you like to use to hold this item?" + "</p>");
//where a function would be stopping the code until a valid answer is given
if (prompt == "1") {
pEQUIP[0] = exItem;
} else if (prompt == "2") {
pEQUIP[1] = exItem;
} else if (prompt == "3") {
pEQUIP[2] = exItem;
}
//Just a quick n dirty way of testing it worked below:
$('#gametext').append("<p>" + pEQUIP[0] + pEQUIP[1] + pEQUIP[2] + "</p>");
//parses user info unsure if this could be used or would have to be copied
$(document).ready(function() {
$(document).keypress(function(key) {
if (key.which === 13 && $('#userinput').is(':focus')) {
var value = $('#userinput').val().toLowerCase();
$('#userinput').val("");
//playerInput(value); Is usually here, would lead to
//a switch which parses commands typed by the user.
//Unsure if it can be used for this problem as pausing
//the code I think would stop the switch?
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div id="gametext"></div>
<input id="userinput">
</body>
It appears as though you're thinking of functions incorrectly.
Functions are:
A series of steps that may return data when they're invoked. You
invoke a function by passing arguments to the function name, even if
the arguments are nothing () - a.e. alert(string) or myFunction()
Not comparable to anything but themselves. In your code you have prompt == "1" this isn't going to work. prompt is a function name and it isn't invoked so you are literally comparing the function itself to the string "1".
Able to return data when invoked. That data can be compared.
Note: Also, very importantly, prompt is the name of a default function(like alert or console) and you shouldn't overwrite it. It isn't considered a reserved keyword by the language but altering it will cause havok if any other library you're using, or any other programmer doesn't know it's been overwritten, and tries to invoke it.
prompt("this is a normal prompt");
Furthermore you have the document setup to check the value of the text box itself on keypress. You should probably change this to an event listener on the text box, but there isn't any reason to continuously loop a function beyond this while waiting for the box to match some predefined input.
The Flow is this:
type in the box
hit enter
check value
if value is 1 or 2 or 3 or any other acceptable answer do something
If that's all you need currently then you do not need to work so hard for the functionality when a single event listener could do the trick:
$("#input_box").on("keypress", function(e) {
if(e.keyCode === 13) {
let value = $("#input_box").val();
if(value === "1" || value === "2" || value === "3") {
//do whatever
}
}
});
$("#input_box").on("keypress", function(e) {
if(e.keyCode === 13) {
let value = $("#input_box").val();
if(value === "1" || value === "2" || value === "3") {
console.log("accepted");
}
$("#input_box").val("");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="input_box">

Can you compare multiple variables to see if they all equal the same value in JS?

Working in Javascript, I am trying to see if 5 different variables all contain the same value at a given time. The value could be 1 of 6 things, but I need to see if they are all the same regardless of which value it is. I have tried this:
if (die1 == die2 & die1 == die3 & die1 == die4 & die1 == die5) {
yahtzeeQualify == true;
}
and this:
if (die1 == die2 == die3 == die4 == die5) {
yahtzeeQualify == true;
}
Are either of these valid? If so, there is probably an error in my code somewhere else...if not, I'd really appreciate some help. I also have these variables in an array called dieArray as follows:
var dieArray = [die1, die2, die3, die4, die5];
It would be cool to learn a way to do this via the array, but if that isn't logical then so be it. I'll keep trying to think of a way on my own, but up until now I've been stuck...
Are either of these valid?
They are "valid" (as in this is executable code) but they don't perform the computation you want. You want to use a logical AND (&&) not a bitwise AND.
The second one is just wrong. You run into type coercion issues and end up comparing die1 to either true or false.
It would be cool to learn a way to do this via the array
You can use Array#every and compare whether each element is equal to the first one:
if (dieArray.every(function(v) { return v === dieArray[0]; }))
// arrow functions make this nicer:
// if (dieArray.every(v => v === dieArray[0]))
Solution with the Array.reduce:
var values = [die1, die2, die3, die4, die5];
var yahtzeeQualify = values.reduce(function(memo, element) {
return element === values[0];
});
The 1st one is what you want, but it's messed up. You want && not &
The 2nd one is logically wrong.
To do it with an array
yahtzeeQualify = dieArray.every(function(n){ return n === dieArray[0] })

Seeing if input matches array if not alert

var tagAllowed = true;
var allowedTags =["Person","People","Dance","Word"];
if(tagAllowed === true) {
for(var i=0;i<allowedTags.length;i++){
var aTags = allowedTags[i];
if(input.val().toLowerCase() === aTags.toLowerCase()) {
tagged.append('<span unselectable="on" class="tagged '+colorize+'" title="Click To Delete">'+inputVal.trim()+'</span>');
tagSize = $('.tagged').length;
var ele = $('.tagged').last(),
subtract = parseInt(ele.outerWidth(true),10);
input.width(input.width() - subtract);
tagged.width(tagged.width() + subtract);
input.css('marginLeft','5px');
input.val("");
input.css('color','#000');
} else {
errorMess.children('span').remove();
errorMess.prepend('<span>'+errorProcess+'<span>');
errorMess.slideDown();
}
}
The following code works in a way, if the input.val() does not match it will show the custom alert errorMess and well even if the word matches it still shows the custom alert. I am wondering if maybe I am doing something wrong in my conditional. As I don't need the custom alert to appear if the words match.
If any suggestions please post. I know this isn't the best example with just a code, but I hope all of you get what I am trying to say. I just don't want the custom alert to appear if the two words match together.
You have the if-statement inside the for-loop. The input value will never equal more than one of the tags in the array. You could use a for-loop to set a boolean. Then the if-statement could follow the for-loop.
boolean isAllowedTag = false;
for(var i=0;i<allowedTags.length;i++){
var aTags = allowedTags[i];
if(input.val().toLowerCase() === aTags.toLowerCase()) {
isAllowedTag = true;
break;
}
}
if (isAllowedTag) {
// ...
} else {
errorMess.children('span').remove();
errorMess.prepend('<span>'+errorProcess+'<span>');
errorMess.slideDown();
}
}
add a break; after your input.css('color, '#000'); line. also, you should really change those last 3 lines to: input.val("").css({marginLeft:'5px', color:'#000'});. Making calls to .css() is slow, so it's better to do as much as you can in one call.

Finding in a predefined set of text options

Say, I want to see if a DOM element is a block. I can write it in three ways, depending on my mood:
// first way
if (el.currentStyle.display == "block" || el.currentStyle.display == "inline-block" || el.currentStyle.display == "table-cell")
// second way
var blocks = {"block": 1, "inline-block": 1, "table-cell": 1};
if (el.currentStyle.display in blocks)//
// third way
if (el.currentStyle.display.match(/block|inline-block|table-cell/))
I have mixed feeling about all of them. First is too verbose once I have more than one option. Second contains those arbitrary values in the object (where I put 1s this time). Third looks like overkill. (What exactly is bad about overkilling?)
Do you know another, better way? If no, any cons I am missing about these three ways?
Javascript only, please.
I like the third way; I don't think it looks like overkill at all. If you need an even shorter way then this works too:
el.currentStyle.display.match(/(e-)?(block|cell)/)
But that's not very readable...
It might be worth abstracting it all away by extending the String prototype:
String.prototype.matches = function(what) {
return (',' + what + ',').indexOf(',' + this + ',') > -1;
};
// Using it:
el.currentStyle.display.matches('block,inline-block,table-cell');
If we're primarily aiming for readability, and if this is happening more than once -- perhaps even if it is just once -- I'd move the test to a function. Then define that function whichever way you like -- probably option 1, for max simplicity there.
Overkill? Possibly. But a gift to the programmer who wants to scan and understand the code 6 months from now. Probably you :-)
function isBlock(el) {
return (el.currentStyle.display == "block" ||
el.currentStyle.display == "inline-block" ||
el.currentStyle.display == "table-cell");
}
// ...
if (isBlock(el)) {
// do something
}
Can't you use the 2nd way but check if it's undefined and then skip the ": 1" part. I haven't tested though.
It looks like you need an inArray function, here is one from the top search result:
Array.prototype.inArray = function (value) {
var i;
for (i=0; i < this.length; i++) {
if (this[i] === value) {
return true;
}
}
return false;
};
Then the forth way would look like this:
if (['block','inline-block','table-cell'].inArray(el.currentStyle.display))
Or in a more readable manner:
var isBlock = ['block','inline-block','table-cell'].inArray(el.currentStyle.display);
My prefered solution for this is:
'block||inline-block||table-cell'.indexOf( el.currentStyle.display ) >= 0
I think that this will use native code of the string and be way more efficient than the array & iteration method.

Categories

Resources