是否有更简洁的方法来旋转数组?

时间:2017-01-06 13:26:55

标签: javascript

基本上我有一个函数可以更新全局下一个值,如果你最后一个重新开始。这似乎是实现这一目标的一种非常复杂的方式,但我不知道更好。

var state
next () {
    const states = [false, 'zoomIn', 'addBg', 'zoom', 'removeBg', 'zoomOut']
    const i = states.indexOf(this.state.zoom)
    state = typeof states[i + 1] !== 'undefined' ? states[i + 1] : false
}
next()

2 个答案:

答案 0 :(得分:3)

如果您想保留state变量,请替换

state = typeof states[i + 1] !== 'undefined' ? states[i + 1] : false

state = states[(i+1)%states.length]

Remainder operator

否则通过使用工厂来保持功能会更清晰:

var next = (function(){
    const states = [false, 'zoomIn', 'addBg', 'zoom', 'removeBg', 'zoomOut'];
    var i = 0;
    return function(){
        return states[(i++)%states.length];
    }
})();
next(); => returns the next state

答案 1 :(得分:0)

也许您可以像states.length那样使用mod:

var state
next() {
  const states = [false,'zoomIn', 'addBg', 'zoom', 'removeBg', 'zoomOut'];
  const i = states.indexOf(this.state.zoom);
  state = states[(i+1)%states.length];
}
next ();