JS. check if the array has a user-defined value through a tooltip

I'm new to web design, just learning CC now. now trying to program my own text game js, in terms of learning js. I am stuck with arrays. I have a predefined array with strings that needs to be compared with the user's response, but the comparison was not performed.

    var myArray = ['selection 1', 'selection 2', 'selection 3', 'selection 4', 'selection 5', 'selection 6', 'selection 7', 'selection 8'];
    alert("text description of scene and dimensions"); 
    var dmg_start = Math.floor((Math.random() * 50) + 1); // pre-start damage dimension, will be used further
    var user = prompt("make a selection").toLowerCase();

first idea how to do it:

if (user.indexOf(myArray) > 0) {
console.log(user); // or mb document.write?
} else {
var user = prompt("make a selection").toLowerCase();
}
alert(myArray + "you can choose following");

Second idea:

    var find = function (myArray, user) {
    for (var i = 0; i < myArray.length; i++) {
             if (myArray[i] == user) {return i;
                 }
      }
       return null;
   };

Third idea:

do
{
    var user = prompt("make a selection").toLowerCase();
}
while (myArray.indexOf(user); // in idea, here must be checking for existence user given value in array
alert(myArray + "you can choose following");

also, I think that you can take a break after the first incorrect data entry with the alert alert (myArray + "you can choose the following"); to help the user make a decision, then use a continuation loop.

In some cases, I have two iterations of the loop, then an interrupt loop, even if the user gives the wrong (not contained in the array) value in the loop.

. ?

.

+4
2

...

var someArray = ['selection 1', 'selection 2', 'selection 3'];
var someIndex = -1;

do {
    var someUser = prompt("make a selection").toLowerCase();
    for (var i = 0; i < someArray.length; i++) {
        if (someArray[i] === someUser) {
            someIndex = i;
            break;
        }
    }

    if (someIndex > -1) {
        alert('found at index: ' + someIndex);
    } else {
        alert('not found: please try this...');
        // or something more put here
    }
}
while (someIndex === -1);
0

, .

if (user.indexOf(myArray) > 0) {

while (myArray.indexOf(user))

indexOf() -1, >= 0.

: IST 09:11 19 2015

max 2:

var fruits = ['apple', 'mangoe', 'grape'];
var cnt = 2; //max attempt
var inp; // for user input
var pos;
do {
  inp = prompt('Name a fruit').toLowerCase();
  pos = fruits.indexOf(inp);
  if (-1 === pos)
    alert('Fruits available: ' + fruits);
} while (--cnt); //upto max attempts
0

Source: https://habr.com/ru/post/1598365/


All Articles