jeudi 9 avril 2020

JavaScript arr.index.of() always gives -1

I have a random number generator and a pick of one of the numbers inside. I'm trying to get the position of the number, So I used index.of() but it always shows '-1'. I thought this would be the most direct way of finding the location of a particular number within an array. Am I wrong?

const shuffle = arr => {
  let a = arr.slice(0); // take a copy
  for (let i = a.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [a[i], a[j]] = [a[j], a[i]];
  }
  return a;
};
var arr = [];
var UserNumber = 10;
var BallNumber = 4;
var RandomNumber = Math.floor(Math.random() * UserNumber) + 1;
while (arr.length < BallNumber) {
  var r = Math.floor(Math.random() * UserNumber) + 1;
  if (arr.indexOf(r) === -1) {
    arr.push(r);
  }
  console.log(r);
}
  var selected = shuffle(arr).slice(0, 1);
document.write("<p> The random Number to choose is " + selected + "</p>");
document.write("<p> The Random Numbers are " + arr + "</p>");
document.write("<p> The position is " + arr.indexOf(selected) + "</p>");



Aucun commentaire:

Enregistrer un commentaire