2010-09-22 72 views
0

嘿所有..我需要一個函數,將返回一個前一個和下一個數字,但只在我的數字範圍內。例如,如果我的範圍是從0到7,並且im在6 - 下一個應該返回7.如果im在7 - 下一個應該返回0(它回到它)。前一個/下一個數字範圍內

與以前相同,如果im爲0,以前應該是7.我認爲modulo可以用來解決這個問題,但不知道如何。該函數應該有3個參數 - 我們所在的當前編號,最大編號以及我們是前進還是後退。像

getPreviousOrNext(0,7, 「下一步」 或 「上一頁」)

感謝!

回答

1

這是一個家庭作業?
我不會使用模數,一些if/ternary語句應該是足夠的。

+0

沒有它不是..其工作...但我不想使用一堆如果else語句...孤單一定有更簡單的方法。 – toli 2010-09-22 22:26:13

+1

是的,if/else很難。 – GZipp 2010-09-22 22:41:50

+0

我覺得他的觀點可能是if/else不是優雅 – Mark 2010-09-22 22:44:47

2

使用模..

function getPreviousOrNext(now, max, direction) { 
    totalOptions = max + 1; //inlcuding 0! 

    newNumber = now; // If direction is unclear, the number will remain unchanged 
    if (direction == "next") newNumber = now + 1; 
    if (direction == "prev") newNumber = now + totalOptions - 1; //One back is same as totalOptions minus one forward 

    return newNumber % totalOptions; 
} 

(可以更短,但是這使得它更容易理解)

編輯: 「現在+共TOTALOPTIONS - 1」 阻止我們進入負數( - 1%7 = -1)

Edit2:Ouch,代碼中有一個小錯誤...「如果方向不清楚,數字將保持不變」是不正確的!

編輯3:爲了獲得獎勵,這是我在閱讀代碼完成之前將它寫出來的原因;-)(假設它不是'prev'就是'next')。這是醜陋和美麗的一個:

function getPreviousOrNext(now, max, direction) { 
    return (now + ((direction=="prev")?max:1)) % (max + 1); 
} 
+0

不錯。 ----- – webbiedave 2010-09-22 22:35:45

+0

以爲我發現了一個錯誤,但不,它很漂亮! :) +1 – DashK 2010-09-22 23:21:41

+0

是的,很好的,謝謝! – toli 2010-09-24 14:11:25

1
var cycle_range = function (high, current) { 
    return new function() { 
     this.next = function() { 
      return current = (current+1) % (high+1); 
     }; 

     this.previous = function() { 
      return current = (current+high) % (high+1); 
     }; 
    } 
}; 

cycle_range(7, 0).next() // 1 

var the_range = cycle_range(7, 0); 
the_range.next() // 1 
the_range.next() // 2 
the_range.previous() //1 
the_range.previous() //0 
the_range.previous() //7 
+0

OO解決方案,很好! – Jochem 2010-09-23 07:23:58

相關問題