Getting new colors randomly with loop

时间:2018-05-22 06:00:58

标签: javascript do-while

I am trying to randomize colors by generating random number, then applying it to array to get an color array containing font-color and background-color.

At every "skill" I want to have unique color scheme. So each time I loop skill array I loop color array to fetch color scheme. If this color scheme number (which is same as the randomNumber) is already in use I random again. I do this with do/while loop. When color is not found it pushes it to usedColors array and paints the picture.

For some reason I am still getting same colors. I pasted two pictures to the bottom. Console.log image is about usedColors array (the randomly generated numbers)

var usedColors = [];
    $.each(knowledges, (i, knowledge) => {                                  
       do {
          var r = Math.floor(Math.random() * Math.floor(colors.length)),
              rColors = colors[r];                

          } while ($.inArray(r, usedColors) == 0);
          usedColors.push(r);

          $("#knowledges div").append(            
              $("<p />").addClass("knowledge").text(knowledge).css({"background-color": rColors[0], "color": rColors[1]})
          );
    });

enter image description here

提供文件链接

enter image description here

4 个答案:

答案 0 :(得分:0)

inArray给出匹配元素的位置。因此,与-1进行比较,要知道usedColors数组中不存在该元素。

&#13;
&#13;
var usedColors = [];

$.each(knowledges, (i, knowledge) => {                                  
   do {
      var r = Math.floor(Math.random() * Math.floor(colors.length)),
          rColors = colors[r];                

      } while ($.inArray(r, usedColors) != -1);
      usedColors.push(r);

      $("#knowledges div").append(            
          $("<p />").addClass("knowledge").text(knowledge).css({"background-color": rColors[0], "color": rColors[1]})
      );
});
&#13;
&#13;
&#13;

答案 1 :(得分:0)

在你的while循环中,你在检查数组是否是唯一的?如果是这样,看起来你可能没有正确使用$ .inArray。

将它放在你的while循环中:$.inArray(r, usedColors) !== -1

jQuery.inArray(), how to use it right?

答案 2 :(得分:0)

要从特定时间间隔生成唯一数字数组,您可以执行此操作。 在您的情况下,范围将是0, arr.length - 1

// function that will generate random unique random numbers between start 
// and end, and store already generated numbers in closure
function generateUniqueRandom(start, end) {
  const used = [];

  function generateInner() {
    let r;
    while (!r) {
      r = Math.floor(Math.random() * (end - start) + 1) + start;
      if (used.includes(r)) {
        r = null;
      } else {
        used.push(r);
      }
    }

    return r;
  }

  return generateInner;
}

const random1 = generateUniqueRandom(0, 20);

const nums1 = [];
for (let i = 0; i < 10; i++) {
  nums1.push(random1());
}

console.log(nums1);

const random2 = generateUniqueRandom(0, 20);

const nums2 = [];
for (let i = 0; i < 20; i++) {
  nums2.push(random2());
}

console.log(nums2);

但是你需要注意不要生成指定范围的更多数字,否则你将陷入无限循环。

答案 3 :(得分:0)

我认为你的循环方法有很多交互,我的意思是你的循环行进太多,只有你找到不在数组中的随机数(A short performance problem)才会结束。另一个method,以便数组元素是随机的:

&#13;
&#13;
function shuffleArray(a) {
    for (let i = a.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [a[i], a[j]] = [a[j], a[i]];
    }
    return a;
}

const colors = [["black","green"], ["white","blue"], ["pink","white"]];
let usedColors = shuffleArray(colors);

//You can now do this:

$.each(knowledges, (i, knowledge) => {
    $("#knowledges div").append(            
        $("<p />").addClass("knowledge").text(knowledge).css({"background-color": usedColors[i][0], "color": usedColors[i][1]})
    );
});
&#13;
&#13;
&#13;