0

Here's a beginner JS question. I'm making a simple app that takes the days I work, the day of the week and then alert's me if I work today.

//
var daysIWork = [
  'Wednesday',
  'Friday',
  'Saturday',
  'Sunday',
];

var dayToday = 'Saturday'; // I'll be changing this to a more advanced method, getDay? When I've figured out how to post this correctly.

for (var i = 0; i < daysIWork.length; i++) {
   console.log(daysIWork[i])
}; // This posts the array correctly, yay.

This is where I'm stuck. If I input a number that matches an array number ie [1] instead of [i], the statement will pop up true. However with the code below, it always turns out false.

if (dayToday === daysIWork[i]) {
   alert ('Noooo, you work today!');
} else {
   alert ("Yes, you don't work today!");
}

I know how to get it working using the array call [1] [2] etc but I can't get it to read a whole array and come back as true.

Thanks.

7
  • 1
    Where do you have your if? It works fine when placing it in the loop: jsfiddle Commented Feb 14, 2015 at 16:27
  • Rereading the question you actually want to detect if the day dayToday is within daysIWork or not. So you actually would use daysIWork.indexOf(dayToday) !== -1 to check if it is in the array. For IE 8 and before your would need to use a polyfill MSN: Array.prototype.indexOf(). Commented Feb 14, 2015 at 16:42
  • Ok that works but it's going through the whole array and posting. IE my 4 items, returns 3 false and 1 true which makes sense in the current code. However I just want one true and one false to come back. If dayToday and a day in the daysIWork match up post true if not post one false alert. Commented Feb 14, 2015 at 16:43
  • So that would go within the for or if niese. Commented Feb 14, 2015 at 16:57
  • Whats wrong with the daysIWork.indexOf(dayToday) !== -1 ? Commented Feb 14, 2015 at 16:58

1 Answer 1

1

    var daysIWork = [
      'Wednesday',
      'Friday',
      'Saturday',
      'Sunday',
    ];

    var dayToday = 'Saturday';


    if (daysIWork.indexOf(dayToday) > 0) {
      console.log('boo');
    } else {
      console.log('yay')
    }

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.