【问题标题】:Increment and Decrement through array using modulus operator or Js使用模运算符或Js通过数组递增和递减
【发布时间】:2017-03-31 04:00:27
【问题描述】:

我能够通过阅读另一个问题来弄清楚如何通过我的数组进行递增。现在我似乎无法弄清楚如何减少,因为我的值被设置回 0。我试图避免循环。

我希望达到的顺序是:

增量 ---- "/", "/about", "/list"

let i = 0;    
let stuff =["/", "about","list"];

next() {
    this.props.dispatch(increaseCounter())
    i = (i+1)%stuff.length;
  }
  prev() {
    this.props.dispatch(decreaseCounter())
    i = (i-1)%stuff.length; <------This gets wonky once I reach the end of my array.
  }

【问题讨论】:

  • 你想要增量值去:0, 1, 2, 0, 1, 2... 和减量 2, 1, 0, 2, 1, 0... 吗?
  • 嘿,Fubar,它绑定到另一个组件中。所以我要做的就是递增:0,1,2 然后什么都不返回。递减 2,1,0 什么也不返回
  • @user992731 对于“然后不返回任何内容”,只需使用 if 语句。
  • 谢谢Bergi,成功了

标签: javascript increment modulus


【解决方案1】:

% 的问题在于它是一个带有截断除法的余数运算符,而不是一个带有地板除法的 modulo。当除数 (i-1) 变为负数时,结果也是如此。你可以使用

if (--i < 0) i = stuff.length - 1;

i = (i + stuff.length - 1) % stuff.length;

改为(不过,它仅适用于预期范围内的 i 输入值)

【讨论】:

    【解决方案2】:

    如果您希望next()02prev() 之间递增i20 之间递减,您可以使用以下命令:

    next() {
        this.props.dispatch(increaseCounter());
        i = Math.min(i + 1, stuff.length - 1);
    }
    
    prev() {
        this.props.dispatch(decreaseCounter());
        i = Math.max(i - 1, 0);
    }
    

    【讨论】:

    • 增量就像一个魅力。一旦到达末尾,减量就会在我的数组中跳过 1。所以它登陆“/list”然后应该回到“about”它目前没有返回任何东西,直到第二次点击登陆“/”
    • 对不起,错字。第二个应该是Math.max
    猜你喜欢
    • 2016-04-05
    • 2011-02-16
    • 1970-01-01
    • 2015-10-03
    • 2014-03-21
    • 1970-01-01
    • 2015-02-16
    • 2010-12-01
    相关资源
    最近更新 更多