Hello everybody. That's my first code using JS. How can I pick a random value from an array with string values? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Hello everybody. That's my first code using JS. How can I pick a random value from an array with string values?

23rd May 2020, 10:26 PM
Julmiste Fils Noel
Julmiste Fils Noel - avatar
7 Answers
+ 3
This way var s=["hello","spam","eggs"] var a=s.length; var b=Math.floor(Math.random()*a); console.log(s[b]);
23rd May 2020, 10:37 PM
Abhay
Abhay - avatar
+ 6
Noël Julmiste Fils let str="python"; console.log(str.slice(0,2)); //Output: py
23rd May 2020, 11:12 PM
CoffeeByte
CoffeeByte - avatar
+ 4
function random(arr){ return arr[Math.floor(Math.random()*arr.length)]; } var myArr= ["a" , "b" , "c"]; console.log(random(myArr));
23rd May 2020, 10:41 PM
CoffeeByte
CoffeeByte - avatar
+ 2
Thanks
23rd May 2020, 10:38 PM
Julmiste Fils Noel
Julmiste Fils Noel - avatar
+ 2
Thank you Luis
23rd May 2020, 10:44 PM
Julmiste Fils Noel
Julmiste Fils Noel - avatar
+ 2
Thank you Mirielle,luis calderón,Abhay
24th May 2020, 12:00 PM
Julmiste Fils Noel
Julmiste Fils Noel - avatar
+ 1
How can I slice like this in Js: name="python" print(name[0:3]) will print "pyt". Please give me the way to use this in Js.
23rd May 2020, 10:57 PM
Julmiste Fils Noel
Julmiste Fils Noel - avatar