Here is an example on jsfiddle
var words = ["monitor", "program", "application", "keyboard", "javascript", "gaming", "network"];
var word = words[Math.floor(Math.random() * words.length)];
console.log(word);
document.getElementById("word").textContent = word;
And to have it fit in directly with you present code:
var getRandomWord = function () {
return words[Math.floor(Math.random() * words.length)];
};
Answer from Xotic750 on Stack OverflowHere is an example on jsfiddle
var words = ["monitor", "program", "application", "keyboard", "javascript", "gaming", "network"];
var word = words[Math.floor(Math.random() * words.length)];
console.log(word);
document.getElementById("word").textContent = word;
And to have it fit in directly with you present code:
var getRandomWord = function () {
return words[Math.floor(Math.random() * words.length)];
};
Try using it this way:
var getRandomWord = (function () {
var gameWordArray = [];
gameWordArray.push("monitor");
gameWordArray.push("program");
gameWordArray.push("application");
gameWordArray.push("keyboard");
gameWordArray.push("javascript");
gameWordArray.push("gaming");
gameWordArray.push("network");
return function () {
var randNum, finalWord;
randNum = Math.floor(Math.random() * gameWordArray.length);
finalWord = gameWordArray[randNum];
return finalWord;
};
})();
DEMO: http://jsfiddle.net/bCEFA/1/
Instead of declaring an array with a predefined length, you might as well declare an empty one and add values to the end of it (with .push()). You could've also declared the array like:
var gameWordArray = ["monitor", "program", ...];
You were trying to print word (which I renamed to getRandomWord), which was/is a function. You probably meant to use console.log(gameWordArray[randno]), which should work.
How can I make a function that chooses a random word everytime I recharge the page?
javascript - Create N digit random words from an array - Stack Overflow
How to generate random words in JavaScript? - Stack Overflow
Randomize wordset javascript array - Stack Overflow
It's basically a wordle. I want it to choose a random word, how can I do that?
You can make use of Array.from and get the word of length length
Array.from({ length }, () => arr[Math.floor(Math.random() * arr.length)]).join("")
Create a dynamic length using
arr.length // instead of 9(Don't hardcode)
const words = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "k"];
function generateRandomWord(arr, length) {
return Array
.from({ length },() => arr[Math.floor(Math.random() * arr.length)])
.join("");
}
console.log(generateRandomWord(words, 4));
console.log(generateRandomWord(words, 8));
console.log(generateRandomWord(words, 12));
This is a functional approach. First call you pass the target array to choose items from, then the next call is the amount.
const numbers = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0'];
const words = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'k'];
function randomNum(target) {
const newRandomNum = (num = 1, val = "") => {
val += (target[Math.floor(Math.random() * 9)])
if (num === 1) return val;
return newRandomNum(--num, val);
}
return newRandomNum;
}
console.log(randomNum(numbers)(5));
console.log(randomNum(numbers)(10));
console.log(randomNum(words)(5));
console.log(randomNum(words)(10));
An improvement you could make is to check the type of the target array, then use += for strings, and another method for numbers since you don't want to add them.
Use:
var things = ['Rock', 'Paper', 'Scissor'];
var thing = things[Math.floor(Math.random()*things.length)];
alert('The computer chose:' + thing);
Demonstration
Just to precisely answer your question, supposing you really want to keep your three global variables, you could do this:
var c = "Rock";
var d = "Paper";
var e = "Scissors";
var thing = window['cde'.charAt(Math.floor(Math.random()*3))];
document.write('The computer chose: ' + thing);
Demonstration
(But don't.)
You can use Math.random() to get a random number beteween 0 and 1.
If you want a whole random number between 0 and 2. (so: 0, 1 or 2). You can use:
Math.floor(Math.random()*3);
Note that Math.round (instead of floor) would be wrong here since the edge values will have a lower chance, and you might actually get 3 as well.
I hope the commented code below helps you:
let words = ["monitor", "program", "application", "keyboard", "javascript", "gaming", "network"];
let getRandomWord = function () {
return words[Math.floor(Math.random() * words.length)];
};
//generating first word
let word1 = getRandomWord();
let word2
do{
//getting the second word and making sure it is diferent from the first word
word2 = getRandomWord();
}while(word1==word2)
console.log(word1, word2);
document.getElementById("word").textContent = word1 + ' ' + word2;
you can simply shuffle your array
const words =
[ 'monitor', 'program', 'application', 'keyboard'
, 'javascript', 'gaming', 'network'
]
for (let i = words.length; --i;) // shuffle Array
{
let j = Math.floor(Math.random() * (i + 1));
[words[i], words[j]] = [words[j], words[i]]
}
// get 2 random words
console.log( words[0], words[1] )
How do I implement the word length specification?
You loop picking up words randomly unless length meets your requirements or you i.e. keep words grouped by length (i.e. multi dimensional array). Then you just need to pick up the right array (your arr) and pick as you did so far
Why not Mapping it first and then Apply your call?
// Example:
const requiredLength = 5,
const originalArr = ['lalal', 'hehehehehe', 'uhuhuhuh', 'uooou'];
const arr = originalArr.map(word => word.length === requiredLength);
// arr = ['lalal','uooou'];
const word = arr[Math.floor(Math.random()*arr.length)];
It's a simple one-liner:
const randomElement = array[Math.floor(Math.random() * array.length)];
For example:
const months = ["January", "February", "March", "April", "May", "June", "July"];
const random = Math.floor(Math.random() * months.length);
console.log(random, months[random]);
If you've already got underscore or lodash included in your project you can use _.sample.
// will return one item randomly from the array
_.sample(['January', 'February', 'March']);
If you need to get more than one item randomly, you can pass that as a second argument in underscore:
// will return two items randomly from the array using underscore
_.sample(['January', 'February', 'March'], 2);
or use the _.sampleSize method in lodash:
// will return two items randomly from the array using lodash
_.sampleSize(['January', 'February', 'March'], 2);
Yes, that's possible, using the Math.random function to generate the text and innerHTML to fill a div.
The array make it easier to get the words.
var tokens = ['Apple', 'Banana', 'The' ...];
var text = '';
for (var i=0; i<50; i++) {
text += tokens[Math.floor(Math.random()*tokens.length)];
}
document.getElementById('myDiv').innerHTML = text;
Yes, use an array. To get a random word from such an array, use the following:
function getRandomWord() {
var words = ['Apple','Banana','The','Orange','House','Boat','Lake','Car','And'];
return words[Math.floor(Math.random() * words.length)];
}
Then invoke that function to whatever extent you like.
var paragraph = [];
for(var i = 0; i < 50; i++)
paragraph.push(getRandomWord());
$('#my-container').text( paragraph.join(' ') );
» npm install random-words