且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

返回均匀的“间隔”大数组中的索引数。

更新时间:2022-12-20 15:35:09

当您需要7个均匀分布的Math.ceil(20/7)= 3时,您可以执行以下操作:

  var selectedColors = []; 
for(var i = 0; i< 20&&selectedColors.length< 7; i + = 3)selectedColors.push(defaultColors [i]);

当您需要10个均匀分布的Math.ceil(20/10)= 2时,可以做到:

  var selectedColors = []; 
for(var i = 0; i< 20&&selectedColors.length< 10; i + = 2)selectedColors.push(defaultColors [i]);


I have a Javascript array of 20 RGB color values that looks like this:

defaultColors: [ rgb(58, 185, 180)','rgb(63, 186, 172)','rgb(71, 185, 159)','rgb(80, 185, 146)','rgb(90, 186, 132)','rgb(103, 187, 119)','rgb(117, 188, 104)','rgb(137, 193, 96)','rgb(163, 200, 90)','rgb(189, 206, 87)','rgb(212, 214, 86)','rgb(232, 219, 87)','rgb(245, 221, 89)','rgb(254, 221, 87)','rgb(254, 216, 83)','rgb(254, 206, 78)', 'rgb(253, 193, 72)','rgb(251, 178, 66)','rgb(244, 163, 63)','rgb(240, 150, 60)']

At any given time I may only need, say, 7 of these colors, but I want to pull colors from the full spectrum. I don't just want the first 7 colors. I'd need something more like this:

Or say I need 10 colors. That would look more like this:

Suggestions around how to pull this off?

When you need 7, evenly spaced, Math.ceil(20/7) = 3, so you can do:

var chosenColors = [];
for(var i =0; i<20 && chosenColors.length<7; i+=3) chosenColors.push(defaultColors[i]);

When you need 10, evenly spaced, Math.ceil(20/10) = 2, so you can do:

var chosenColors = [];
for(var i =0; i<20 && chosenColors.length<10; i+=2) chosenColors.push(defaultColors[i]);