如何使用随机值进行输入:
例如: 我有3个可能的输入值:
**VALUE 1**;
**VALUE 2**;
**VALUE 3**;
我希望随机自动地在输入中输入这3个值中的一个。
答案 0 :(得分:2)
这样的东西?
var x = Math.random();
var y;
if (x < 1/3)
y = "VALUE 1";
else if (x < 2/3)
y = "VALUE 2";
else
y = "VALUE 3";
alert(y);
假设您希望以相同的概率选择每个值。
答案 1 :(得分:1)
var randomvalue = ['one','two','three'];//set what values you want
var index = Math.floor(Math.random() * (2 - 1 + 1));//generate random number for index
console.log(index)
//Note:set 2 as max and 1 as min because in array i set only 3 values so the number will be random from 0-2 where 0 is first item because it is index
$("#test").val(randomvalue[index])//setting the random value as input text
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="test"/>
&#13;
.val()
设置随机值答案 2 :(得分:0)
首先,您需要一个具有可用值的数组:
const arr = ['Value 1', 'Value 2', 'Value 3'];
然后,您要选择一个random element from that array来创建input
:
const arr = ['Value 1', 'Value 2', 'Value 3'];
// Pick a random element from `arr`:
const random = arr[Math.floor(Math.random() * arr.length)];
// Create the field:
const $input = $('<input />', {
value: random
});
// Insert the element into the page body:
$input.appendTo('body');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>