返回均匀的“间隔”大数组中的索引数。 [英] Returning an evenly "spaced" number of indexes from a large array.

查看:65
本文介绍了返回均匀的“间隔”大数组中的索引数。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含20个RGB颜色值的Javascript数组,如下所示:

  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)'] 

在任何给定时间我只能需要其中7种颜色,但是我想从整个光谱中提取颜色。我不只是想要前7种颜色。我需要这样的东西:





或者说我需要10种颜色。看起来更像这样:





有关如何实现此目标的建议?

解决方案

当您需要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]);

这篇关于返回均匀的“间隔”大数组中的索引数。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆