为具有类似排序条件的数组中的变量赋值

assigning a value to a variable from an array with a sorting like conditions

本文关键字:数组 变量 赋值 条件 排序      更新时间:2023-09-26

在下面的代码中,我想将值数组的随机元素分配给值value1 value2 我能够做到这一点,但现在我想确保 value1 低于值 2。 你看到"TBSP"比"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},

试试这个:

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]];
}

第一个夹紧1values.length - 1之间的范围,第二个夹紧0value1 - 1之间的范围。