在下面的代码中我想将值数组的随机元素分配给值value1
value2
我能够做到这一点,但现在我想确保value1低于value你看到""小于" fl-oz"和杯子比品脱等小。
function unit(){
var values = ["tbsp", "fl-oz", "cups", "pint/s", "Quarts" , "Gallon/s"],
value1 = values[Math.floor(Math.random() * values.length)];
value2 = values[Math.floor(Math.random() * values.length)]
if(value1 !== value2){
return [value1, value2]
}
}
我正在考虑做一些事情,比如将数组元素变成像var values = [{item : "tbsp" , rank : 1 }, {item : "fl-oz" , rank : 2}, {item : "cups" , rank : 3},
答案 0 :(得分:0)
试试这个:
function unit(){
var values = ["tbsp", "fl-oz", "cups", "pint/s", "Quarts" , "Gallon/s"],
value1 = Math.floor(Math.random() * (values.length - 1)) + 1,
value2 = Math.floor(Math.random() * value1);
return [values[value2], values[value1]];
}
第一个夹住1
和values.length - 1
之间的范围,第二个钳位范围介于0
和value1 - 1
之间。