JavaScript - an array in if statement - javascript

I really need some help with this one, I've been struggling a lot trying to crack the example down on my own for way too long.. the whole issue is that I have an array that includes 15 pictures added by push property & createImage function, the problem though is that I've absolutely no idea how I could use the image in an if-statement like so:
if (check both if the image displayed is the first image within the array and answer equals 'x') return that's a good answer
that's a good answer } else (in case if either the image isn't the first one or answer doesn't equal 'x' return that's not a good answer
So far I've achieved the following, unfortunately enough the program omits the rule regarding the array
var answer = document.getElementById("answer");
var image = newArray[0];
function check() {
if (newArray[0] == true && answer.value == "C") {
window.alert("that's a good answer");
} else if (newArray[0] == true && answer.value == "c") {
window.alert("that's a good answer as well");
} else {
window.alert("that's unfortunately not a good answer");
}
}
Thanks in advance for any form of help

I obviously had to change things a bit since you don't give us the document or newArray, but after adding some dummy data and running it, it works. Can you be more specific about the error(s) you're running into?
Here's my solution:
var answer = "C";
var newArray = [true, false, false, true];
var image = newArray[0];
function check() {
if (image === true && answer == "C") {
window.alert("that's a good answer");
} else if (image === true && answer == "c") {
window.alert("that's a good answer as well");
} else {
window.alert("that's unfortunately not a good answer");
}
}
check();

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] })

jquery filter by two variables & one of them maybe undefined

I'm writing some jquery code to filter li items based on class & data-attribute.
Here is the code: http://pastebin.com/14eLwYWP
The problem is, that when one of the variables is undefined (which happens when user click second time to disable filter), it doesn't show anything. I was wondering that is there any other resolution to this problem, instead of writing code for every case.
I mean, situation is simple, each() filters only when both currentCity and currentAge has values. But when one of them is undefined, I want to show li-items filtered by only another one variable. I don't know how to write it, but I think the main problem is there:
$('ul.the_loop').children('li').each(function() {
if ($(this).data('age') == 'post_' + currentAge && $(this).hasClass("tag-" + currentCity)) {
$(this).show();
} else if (currentAge == undefined || currentCity == undefined) {
//don't know what to do there, both with logic and code...
} else {
$(this).hide();
}
});
Hope you guys will help me ;)
Have a nice day & cheers!
EDIT: Because this code, as stupid it is, works…
$('ul.the_loop').children('li').each(function() {
if ($(this).data('age') == 'post_' + currentAge && $(this).hasClass("tag-" + currentCity)) {
$(this).show();
} else if (currentAge == undefined && $(this).hasClass("tag-" + currentCity)) {
$(this).show();
} else if ($(this).data('age') == 'post_' + currentAge && currentCity == undefined) {
$(this).show();
} else if (currentAge == undefined && currentCity == undefined) {
$(this).show();
} else {
$(this).hide();
}
});
But there must be more elegant way of doing this...
You are checking for equality, so when currentAge is undefined your filter breaks because no element has an age of just "post_" with no age value after it. (As you already know) so if you use indexOf to instead check if the string contains the phrase "post_"+currentAge then it won't break since all of the age attributes begin with "post_". The indexOf function will return the index of where the substring occurs in the string, or -1 if it can't find it. The idea is the same for currentCity and "tag-", but we need a string to look at to do the comparison, so instead of hasClass just use .attr('class') instead, so its
function globalFilter(currentCity, currentAge) {
$('ul.the_loop').children('li').each(function () {
if ($(this).data('age').indexOf('post_' + currentAge) > -1 && $(this).attr('class').indexOf("tag-" + currentCity) > -1) {
$(this).show();
} else {
$(this).hide();
}
}
EDIT: If you are dynamically changing the classes of elements you may need to use .prop('class') instead of .attr

conditional statement, if else if

I am trying to write a if, else if condition, with some luck.
after trying for some time I have some of it working but not fully functional.
simple script to change div style for simple image gallery.
I have the first and third divs working but the second is not showing up.
I seem to understand the concept but in reverse and suspect the problem is in the else if part of the code.
I am not looking for someone to do it for me but to explain where I am reversing things.
Here is what I have working so far, but as I said something is reversed.
any thoughts or better yet explanations would be most appreciated.
function scroll()
{
if (document.getElementById('thumbs1').style.visibility=='hidden' && document.getElementById('thumbs2').style.visibility=='visible' && document.getElementById('thumbs3').style.visibility=='visible' )
{
document.getElementById('thumbs1').style.visibility='visible';
document.getElementById('thumbs2').style.visibility='hidden';
document.getElementById('thumbs3').style.visibility='hidden';
}
else if (document.getElementById('thumbs2').style.visibility=='hidden' && document.getElementById('thumbs1').style.visibility=='visible' && document.getElementById('thumbs3').style.visibility=='visible' )
{
document.getElementById('thumbs1').style.visibility='hidden';
document.getElementById('thumbs2').style.visibility='visible';
document.getElementById('thumbs3').style.visibility='hidden';
}
else
{
document.getElementById('thumbs1').style.visibility='hidden' ;
document.getElementById('thumbs2').style.visibility='visible' ;
document.getElementById('thumbs3').style.visibility='visible';
}
}
the second is not showing up
That's because your code never enters the block that shows it. Your condition for that is that thumbs2 is hidden while thumbs1 and thumbs3 are visible, which is a combination that is not apparent in any of the assignments. Seems like you have confused 1 and 3 somewhere.
Tip for spotting such mistakes easier: Create variables for the style objects and reuse them instead of executing the code to access them every time. That's not only faster, but also makes the code shorter and more readable. Or even better, an array:
var styles = [];
for (var i=0; i<3; i++)
styles[i] = document.getElementById("thumbs"+(i+1)).style;
if (styles[0].visibility=='hidden' && styles[1]=='visible' && styles[2].visibility=='visible') {
styles[0].visibility='visible';
styles[1].visibility='hidden';
styles[2].visibility='hidden';
} else if (styles[0].visibility=='visible' && styles[1].visibility=='hidden' && styles[2].visibility=='visible') {
styles[0].visibility='hidden';
styles[1].visibility='visible';
styles[2].visibility='hidden';
} else {
styles[0].visibility='hidden' ;
styles[1].visibility='visible' ;
styles[2].visibility='visible';
}
If your pattern had been more predictable (like rotating the visibility), a programmatical approach would be possible as well now.
Hard to tell what you're trying to do, but if you want to just reverse all 3:
function scroll()
{
var t1 = document.getElementById('thumbs1'),
t2 = document.getElementById('thumbs2'),
t3 = document.getElementById('thumbs3');
t1.visibility = t1.visibility === "hidden" ? "visible" : "hidden"
t2.visibility = t2.visibility === "hidden" ? "visible" : "hidden"
t2.visibility = t3.visibility === "hidden" ? "visible" : "hidden"
}
or more succinctly
function scroll()
{
var thumbs = [document.getElementById('thumbs1'),
document.getElementById('thumbs2'),
document.getElementById('thumbs3')];
for(var i=0; i<thumbs.length; i++) {
thumbs[i].visibility = thumbs[i].visibility === "hidden" ? "visible" : "hidden";
}
}
First, thanks for the thoughts. I found much understanding in the serious thoughts posted here, and i now am beginning to see the appeal of working with arrays.
The answer was simple and obvious, too many conditions. I used the ideas on variables and used a logical approach. Here is what I came up with.
function scroll()
{
var t1=document.getElementById('thumbs1'),
t2=document.getElementById('thumbs2'),
t3=document.getElementById('thumbs3');
if (t1.style.visibility=='visible' )
{
t2.style.visibility='visible';
t1.style.visibility='hidden';
t3.style.visibility='hidden';
}
else if (t2.style.visibility=='visible' )
{
t1.style.visibility='hidden';
t3.style.visibility='visible';
t2.style.visibility='hidden';
}
else
{
t1.style.visibility= 'visible';
t2.style.visibility='hidden' ;
t3.style.visibility='hidden';
}
}
Simple, huh?
Thanks again.
P.S.
would of posted the solution sooner but had to wait 8 hours to answer my own question.

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.

Simpler way to format if statement?

I have an if statement:
if(firstString == "no" && secondString == "no" && thirdString == "no"){
// Do stuff here
}
Is there a prettier way to format this? Using false instead of "no" is not an option, since the data I'm checking is from an AJAX request and I don't control its output. Otherwise I'd write it this way:
if(!firstString && !secondString && !thirdString){
// Do stuff here
}
Thanks
UPDATE:
I know this is totally ridiculous, but it occurred to me that this might actually be the shortest way:
if(firstString + secondString + thirdString == "nonono"){
// Do stuff here
}
Given that the number of strings is known in advance, then you have 2 options as far as I can see..
Leave it as it is. The if statement isn't hard to read, and any alternate formats will either be as complicated or more complicated.
convert the strings to booleans when you retrieve the data from the AJAX request, so that you're storing TRUE or FALSE instead of "yes" and "no". That would allow you to use a your preferred if statement format, and might be more efficient than many string comparisons if you do a lot of them.
In the end, which you do is up to you, but personally I think it would be better to just stick with what you've got. Don't worry about formatting an if statement, it's pretty obvious what it does, and in my opinion doesn't need to change.
If( "no" == firstString && firstString == secondString && secondString == thirdString )
It was a little difficult to determine exactly what you are evaluating to true or false, but this can be tweaked a tad to get what you're looking for.
var checkStrings = function() {
var no = "no",
args = Array.prototype.slice.call(arguments);
for (var i = 0, len = args.length; i < len; i++) {
if (args[i] !== no) {
return false;
}
}
return true;
};
if (checkStrings(firstString, secondString, thirdString)) {
// Do stuff here
}
Sorry, wasn't thinking--this is if you were checking whether ANY were 'no'
if ($.inArray('no', [firstString, secondString, thirdString]) >= 0) {
// Do something if the value is 'no'
}
UPDATED ANSWER
Unfortunately, jQuery doesn't have the reduce() function (another Array extra introduced in JS 1.6, but not available in older browsers) which would do the trick nicely.
Here's one way to check if all are 'no':
var found = true;
$.each([firstString, secondString, thirdString], function (i, str) {
if (str !== 'no') {
found = false;
}
});
It may seem uglier, but it should be shorter if you have a lot more strings to check.
If you want it wrapped in a function you could do:
function allTrue (arr, checkStr) {
var found = true;
$.each(arr, function (i, str) {
if (str !== checkStr) {
found = false;
}
});
return found;
}
if (allTrue([firstString, secondString, thirdString], 'no')) {
// ...
}
function F(var value){
return value === "no";
}
if(F(firstString) && F(secondString) && F(thirdString)){
// Do stuff here
}
Another option, using jQuery.unique:
var uniques = $.unique([firstString, secondString, thirdString]);
if (uniques.length === 1 && uniques[0] === "no") {
// do stuff
}

Categories

Resources