'Uncaught ReferenceError: floor is not defined' when trying to use floor and random to randomly pick an item from an array

1

I have the following array:

var cartasViradas=[
    'assets/img/1.png',
    'assets/img/2.png',
    'assets/img/3.png',
    'assets/img/4.png',
    'assets/img/5.png',
    'assets/img/6.png',
    'assets/img/7.png',
    'assets/img/8.png',
    'assets/img/9.png',
    'assets/img/10.png'
];

And I would like to know how I can randomly get one of these array values within a variable.

When I try to use the floor and random method in an Ionic 2 .ts extension file, I get the following error:

  

Uncaught ReferenceError: floor is not defined

This is the code that is causing the error:

var selecionado = [];

for (var i = 0; i < 10; i++) { // Escolha aleatoriamente um da matriz cartasViradas
    var randomInd = floor(random(cartasViradas.length));
    var face = cartasViradas[randomInd];
    selecionado.push(face);
    selecionado.push(face);
    cartasViradas.splice(randomInd, 1);
}
    
asked by anonymous 14.10.2017 / 20:39

1 answer

2

floor and random are methods of the Math object. You need to Math.floor and Math.random . Additionally, you were passing length as a parameter to random . The right is to multiply. So change this:

var randomInd = floor(random(cartasViradas.length));

So:

var randomInd = Math.floor(Math.random()*cartasViradas.length);
    
14.10.2017 / 21:30