按数组索引进行颜色分组,Javascript

时间:2017-02-05 17:49:57

标签: javascript arrays

我有以下数组:

const colors = ['#54AAED', '#7BEA6B', '#f8b653', '#ff5584']

我正在尝试构建的是一个基于参数组和索引返回颜色的函数。例如:

function groupColor(i, group) {}

该函数应该返回:

groupColor(0, true); output <== '#54AAED'
groupColor(1, true); output <== '#54AAED' Minus 10% RGB

如果是组,那么索引0是#54AAED 1是#54AAED最小10%不透明度, 索引2是#7BEA6B索引3是#7BEA6B减去10%的不透明度,等等......到目前为止我做过:

function hexToRgb(hex, opacity) {
  return 'rgba(' + (hex = hex.replace('#', '')).match(new RegExp('(.{' + hex.length/3 + '})', 'g')).map(function(l) { return parseInt(hex.length%2 ? l+l : l, 16) }).concat(opacity||1).join(',') + ')';
}

function generateColor({ i, group }) {
  if (group) {
    console.log('should group...')
  }
  const isEven = i % 2 === 0

  console.log('index', hexToRgb(palette[i], 0.9))
  return hexToRgb(palette[i])
}

我想要做的是检查索引是否为奇数,并且通过跳转2个索引组,如果bool为真..但我有点卡在这里...不确定如何按2的间隔进行分组,首先应该瞄准全彩色,然后采用相同颜色并将不透明度设置为0.9 ......

示例用法:

const colors = ['#54AAED', '#7BEA6B', '#f8b653', '#ff5584']
const groupMe = ['one', 'two', 'three', 'four']
groupMe.map(entry => {
 return generateColor(i, true)
})
// expected output
'one' <== '#54AAED' opacity 1
'two' <== '#54AAED' opacity 0.9
'three' <== '#7BEA6B' opacity 1
'four' <== '#7BEA6b' opacity 0.9
and so on...

1 个答案:

答案 0 :(得分:1)

只需检查该数字是否均为上一个索引。并使用三元组来设置不透明度。反应的例子:

&#13;
&#13;
const Component = React.Component
const palette = ['#54AAED', '#7BEA6B', '#f8b653', '#ff5584', '#d743c4', '#76bbf1', '#95ee89', '#f9c575', '#ff9d6d', '#ff779d', '#df69d0', '#9178ec'];
function hexToRgb(hex, opacity) {
  return 'rgba(' + (hex = hex.replace('#', '')).match(new RegExp('(.{' + hex.length/3 + '})', 'g')).map(function(l) { return parseInt(hex.length%2 ? l+l : l, 16) }).concat(opacity||1).join(',') + ')';
}

function generateColor({ i, group }) {
  const isEven = i % 2 === 0
  if (group) {
   return hexToRgb(palette[isEven ? i : i - 1], isEven ? 1 : 0.9)
  }
}

class App extends Component {
  render() {
    const itirations = 10;
    return (
      <div style={{ textAlign: 'center', width: '50%', marign: '0 auto' }}>
        {Array.from(Array(itirations), (_, i) =>
          <div style={{ width: 300, height: 10, marginTop: 10, backgroundColor: generateColor({ i, group: true }) }} />           
        )}
      </div>
    )
  }
}

ReactDOM.render(
  <App />,
  document.getElementById('mount')
)
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="mount"></div>
&#13;
&#13;
&#13;

相关问题