Uncaught TypeError: rand.slice is not a function

I get the following error in the browser console

Uncaught TypeError: rand.slice is not a function

Javascript

var rand, date;
date = Date.now();
rand = Math.random() * Math.random();
rand = Math.floor(date * rand);
rand = rand.slice(-5); 
document.getElementById("test").innerHTML = rand;

I can’t understand what is wrong with this code.

+4
source share
3 answers

you cannot directly chop the number .. you can convert to a string first and then sliceafter

like this:

rand = rand.toString().slice(-5)

JavaScript snippet method Array ()

JavaScript String slices () Method

+13
source

Try using rand = rand.toString().slice(-5);insteadrand = rand.slice(-5);

slicecan be used on arrayeither or stringnot numbers.

+3
source

to try:

rand = (rand+'').slice(-5); 
+3
source

All Articles