1

Can you please explain and show the right answer:

<p id="show"></p>

<script>

var a = "word1";
var b = "word2";

do {
    color = prompt("Write a word1 or word2 to get out of loop", "");
} while (color != a || color != b);

document.getElementById("show").innerHTML=color;

</script>

It works when I delete 'b' option and leave as is only with 'a' option. So how can I use it for multiple options? Also, if you have a solution to keep it simple if I had 15 options for example, it will be great!

Thank you

1

2 Answers 2

4

Checking to see if something is not one thing, or not another thing, will always be true. I think you want && and not ||.

More generally, if you've got lots of options, then if the values are strings (or easily-stringified things) then a good pattern is:

var badValues = {
  "a": 1, "b": 1, "c": 1, ...
};

do {
  color = prompt("Write a word1 or word2 to get out of loop", "");
} while (!badValues[color]);

You could flip the logic around to deal with a "whitelist" instead of a "blacklist".

edit — an insightful comment (now removed) pointed out that my statement that the || comparison will always be true only works when "a" is really different from "b".

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

1 Comment

@Asad well yes but that's what I meant by "another thing" :-)
0

You can simply use an array and check whether the string is in the array.

var words = ["word1", "word2", "word3"];

do {
    color = prompt("Write a " + words.join(' or ') + " to get out of loop", "");
} while (words.indexOf(color) === -1);

document.getElementById("show").innerHTML = color;

4 Comments

There is also String.prototype.indexOf, which works slightly differently but might be preferable, depending on the OPs requirements of course. The good part is that it's supported in ECMAScript ed 3 (so pretty much every browser likely to be in use) and string stuff is very fast. Array.prototype.indexOf is ES5 so should be used with a shim and is likely slower (though probably imperceptibly).
It's supported in IE9+ and all other browsers
While here I sit in a corporate environment where the SOE is IE 8, and know of places still using IE 6.
True. Know that I am sorry for that :P

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.