- Javascript how does random choose randomly from list
- Pick a random item from a list
- How to Pick a Random Element from an Array in Javascript
- Click A Random Element
- How to Randomly Choose Selected Item in Select Dropdown that wasn’t chosen before in JavaScript?
- Choose random function according to condition
- Getting random array from list
- choose up to x number of items from a list in javascript
- 4 Answers 4
- how can I give an array as options to select element?
- 6 Answers 6
Javascript how does random choose randomly from list
To run a specific func, you filter the list by running conditions first and pick a random item from what’s left: Solution 3: «eval» is a good helper for this sutiation; For example we have 5 function and named by «f1, f2, f3, f4, f5» and conditions are boolean values c1, c2, c3, c4, c5 if randomizing select sum contitions for to test program; Solution 1: Super close! Here is a proper version: HTML Modifications: add an attribute name to the input (you had without any attribute key) use an callback, so that something happens when you click your button JS Modifications: wrap your random code into a function (the one referenced by the attribute of your button) assign the result to the input Solution 2: The method below shows how to get a random item in javascript: Solution: Solution 1: I don’t think there’s a reason to get fancy here.
Pick a random item from a list
Your code is almost correct. Here is a proper version:
Modifications:
- add an attribute name to the input (you had «randomSong» without any attribute key)
- use an onclick callback, so that something happens when you click your button
var song = Array("song1", "song2", "song3", "song4", "song5", "song6"); function randomSong()
- wrap your random code into a function (the one referenced by the onclick attribute of your button)
- assign the result to the input
The method below shows how to get a random item in javascript:
const songs = ["song1", "song2", "song3", "song4", "song5", "song6"]; function findSong()
Javascript — Generate unique random numbers between 1 and 100, If a array is not created, A hashMap may be used to remember the actual swapped positions. When the second random number generated is equal to the one of the
How to Pick a Random Element from an Array in Javascript
In this video tutorial, you will learn how to pick a random element from an array in javascript Duration: 3:33
Click A Random Element
Imagine we have a list of items and want to pick an item randomly and click on it. We can Duration: 2:50
How to Randomly Choose Selected Item in Select Dropdown that wasn’t chosen before in JavaScript?
Python Random choice() Method, The choice() method returns a randomly selected element from the specified sequence. The sequence can be a string, a range, a list, a tuple or any other
Choose random function according to condition
I don’t think there’s a reason to get fancy here. Just use some if s to check for your conditions. If a condition applie,s push the corresponding function to an array of possible options . Then select a random value in the array and call it.
const foo = () => console.log("foo"); const goo = () => console.log("goo"); const hoo = () => console.log("hoo"); const cond1 = true; const cond2 = false; const cond3 = true; const options = []; if (cond1) options.push(foo); if (cond2) options.push(goo); if (cond3) options.push(hoo); options[Math.floor(Math.random() * options.length)]();
And for the friends of shorthand:
const foo = () => console.log("foo"), goo = () => console.log("goo"), hoo = () => console.log("hoo"), cond1 = true, cond2 = false, cond3 = true, options = [ . (cond1 ? [foo] : []), . (cond2 ? [goo] : []), . (cond3 ? [hoo] : []), ]; options[Math.floor(Math.random() * options.length)]();
A good data structure for the job would be a list of pairs [condition, function] where condition is also a function. To run a specific func, you filter the list by running conditions first and pick a random item from what’s left:
funcs = [ [ () => x > 10, () => console.log('one'), ], [ () => x > 20, () => console.log('two'), ], [ () => x > 30, () => console.log('three'), ], ] let randomItem = a => a[Math.floor(Math.random() * a.length)] x = 35 // @TODO handle the edge case when no function matches let pair = randomItem(funcs.filter(p => p[0]())) pair[1]()
«eval» is a good helper for this sutiation;
For example we have 5 function and named by «f1, f2, f3, f4, f5» and conditions are boolean values c1, c2, c3, c4, c5
if randomizing select sum contitions for to test program;
function f1() < console.log("f1 fired!"); >function f2() < console.log("f2 fired!"); >function f3() < console.log("f3 fired!"); >function f4() < console.log("f4 fired!"); >function f5() < console.log("f5 fired!"); >var c1 = false; var c2 = true; var c3 = false; var c4 = true; var c5 = false; var selectedFunctionNames = []; function test()< if(c1) selectedFunctionNames.push("f1()"); if(c2) selectedFunctionNames.push("f2()"); if(c3) selectedFunctionNames.push("f3()"); if(c4) selectedFunctionNames.push("f4()"); if(c5) selectedFunctionNames.push("f5()"); if(selectedFunctionNames.length>=1) eval(selectedFunctionNames[Math.floor(Math.random() * selectedFunctionNames.length)]); else console.log("There is no any function have a condition"); >
Randomly select multiple elements from an array (Not a single value, let randArr = []; while(let i = 0; i < n; i++) let chosen = Math.floor(Math.random() * originalarray.length); randArr[i] = originalarray[chosen];
Getting random array from list
Super close! You can just call random.choice(a) where you have random.choices(a) , which should work on any list.
Another way to go about would be to generate a random number between 0 and the length of your list and index your list with that random number.
import random >>> y = [(array([1., 0.]), array([0., 1.])), (array([0., 1.]), array([1., 0.])), (array([0.5, 0.5]), array([0.66666667, 0.33333333]))] >>> random.choice(random.choice(y)) array([0.5, 0.5])
eqs = game.support_enumeration() a = np.reshape(np.array(list(eqs)), (-1, 2)) b = random.choice(a)
How to decide between two numbers randomly using javascript?, The Math.random function chooses a random value in the interval [0, 1) . You can take advantage of this to choose a value randomly.
choose up to x number of items from a list in javascript
I have a list of items where I want the user to be able to select up to three items. I have the below code.
var listItems = document.querySelectorAll('li'); var clickcnt = 0; for(var i = 0; i < listItems.length; i++)< listItems[i].addEventListener('click', function(event) < if(this.hasAttribute('class'))< var test = document.getElementsByClassName('clicked'); this.classList.remove('clicked'); clickcnt--; >else if(clickcnt < 3) < this.classList.add('clicked'); clickcnt++; >console.log(clickcnt); >); >
The issue I am having is that I am checking to see if the item has a class if so I am reducing the click count. But it keeps subtracting the items so if I for example click on item 1 4 times in a row I am then able to select the other four. How can I set this up so the user can keep clicking on an item until they have a max of 3 selected but if they click on the same one twice it removes the item so that it is at its intial state?
4 Answers 4
var listItems = document.querySelectorAll('li'); var toggleClicked = function(event) < var _class = 'clicked'; if (-1 < this.className.indexOf(_class)) < this.classList.remove(_class); >else if (3 > document.getElementsByClassName(_class).length) < this.classList.add(_class); >else < console.warn('Oops !'); >console.log('No. elements:', document.getElementsByClassName(_class).length, 'with class:', _class); >; for (var i = 0; i
var listItems = document.querySelectorAll('li'); var clickcnt = 0; for(var i = 0; i < listItems.length; i++)< listItems[i].addEventListener('click', function(event) < if(this.className)< this.className = ""; clickcnt--; >else if(clickcnt < 3) < this.className = "clicked"; clickcnt++; >console.log(clickcnt); >); >
var listItems = document.querySelectorAll('li'); var clickcnt = 0; var myList = document.querySelector('#mylist'); myList.addEventListener('click', function(event) < var itemClassList, selected, canAdd; itemClassList = event.target.classList; canAdd = clickcnt < 3; if (itemClassList.contains('clicked')) < itemClassList.remove('clicked'); clickcnt -= 1; >else if (canAdd) < itemClassList.add('clicked'); clickcnt += 1; >>);
You can use clickcnt = Math.max(clickcnt — 1, 0); — this picks the maximum value of the two values. If clickcnt — 1 is below 0 it just returns 0 instead. See MDN reference.
Your checking whether there is a class or not will fail though after adding one class and remove it, as it doesn’t remove the attribute, just the class. If you’re using classList then you can use this.classList.contains(‘clicked’) .
var listItems = document.querySelectorAll('li'); var clickcnt = 0; for (var i = 0; i < listItems.length; i++) < listItems[i].addEventListener('click', function (event) < if (this.classList.contains('clicked')) < this.classList.remove('clicked'); clickcnt = Math.max(clickcnt - 1, 0); >else if (clickcnt < 3) < this.classList.add('clicked'); clickcnt++; >>); >
To clean up a bit you can just use one if and the toggle method from the classList object. See this fiddle:
var listItems = document.querySelectorAll('li'); for (var i = 0; i < listItems.length; i++) < listItems[i].addEventListener('click', clicked); >function clicked() < var clickCount = document.getElementsByClassName('clicked').length; var el = this; if (clickCount >= 3) < this.classList.remove('clicked'); >else < this.classList.toggle('clicked'); >>
To have a global variable that’s you can refer to for the click count in other functions you can change the code to:
var listItems = document.querySelectorAll('li'); var clickCount = 0; for (var i = 0; i < listItems.length; i++) < listItems[i].addEventListener('click', clicked); >function clicked() < var el = this; if (clickCount >= 3) < this.classList.remove('clicked'); >else < this.classList.toggle('clicked'); >clickCount = document.getElementsByClassName('clicked').length; >
how can I give an array as options to select element?
I have a select element on my HTML page. I want to populate it with an array. as we can give an array as dataprovider to comboBox in action script. I do the following in HTML.
var videoSrcArr = new Array("option1", "option2", "option3", "option4", "option5");
6 Answers 6
I highly recommend you use a format like the following:
var options = [ < "text" : "Option 1", "value" : "Value 1" >, < "text" : "Option 2", "value" : "Value 2", "selected" : true >, < "text" : "Option 3", "value" : "Value 3" >]; var selectBox = document.getElementById('rec_mode'); for(var i = 0, l = options.length; i
You don’t run in to the problem of having to select a default option and you can easily generate the options array dynamically.
ES6 version of the above code:
let optionList = document.getElementById('rec_mode').options; let options = [ < text: 'Option 1', value: 'Value 1' >, < text: 'Option 2', value: 'Value 2', selected: true >, < text: 'Option 3', value: 'Value 3' >]; options.forEach(option => optionList.add( new Option(option.text, option.value, option.selected) ) );
@haykam You could, but then you can’t designate if one of them is selected. If that’s not part of your requirements, no big deal. Just use an array, map the value to the first parameter and the index to the second.
I would recommend to use object instead of array it will be of great helpful and in respected manner with standards. The reason is WE can index into the object by the «key» and get the «value» . To display contents and resetting them you can follow this NOTES
var myobject = < ValueA : 'Text A', ValueB : 'Text B', ValueC : 'Text C' >; var select = document.getElementById("rec_mode"); for(index in myobject)
This is the simplest way to populate comboBox with an array.
var j = new Array("option1","option2","option3","option4","option5"), var options = ''; for (var i = 0; i < j.length; i++) < options += ''; > $("#rec_mode").html(options);
var videoSrcArr = new Array("option1","option2","option3","option4","option5"), selectEl = document.getElementById('rec_mode'); for(var i = 0; i
—better to use an array literal than the array constructor as it’s less to type and less likely to do unexpected things (e.g. new Array(9) vs [9] .
This is the best way you can get array values in combo box
var states = new Array(); states['India'] = new Array('Andhra Pradesh','Arunachal Pradesh','Assam','Bihar','Chhattisgarh','Goa','Gujarat','Haryana','Himachal Pradesh','Jammu and Kashmir','Jharkhand','Karnataka','Kerala','Madhya Pradesh','Maharashtra','Manipur','Meghalaya','Mizoram','Nagaland','Odisha','Punjab','Rajasthan','Sikkim','Tamil Nadu','Telangana','Tripura','Uttar Pradesh','Uttarakhand','WestBengal','Andaman and Nicobar Islands','Chandigarh','Dadra and Nagar Haveli','Daman and Diu','Lakshadweep','Puducherry'); function setStates() < var newOptions=states['India']; var newValues=states['India']; selectField = document.getElementById("state"); selectField.options.length = 0; for (i=0; i>
State :