2011-11-01 48 views
0

可以說我有8項的序列,這些環以使得8來後1.計算數領先3個地方時在環序列的末端

1,2,3,4,5,6, 7,8

如果選定的項目是數字7,我如何得到前面三個地方的數字,即:2?

我:

var total; // (total number in sequence) 
var pos; // (current position number) 

if (pos < total) { 
    threeIncrement = pos+3; 
} else { 
    threeIncrement = ?????? 
    } 

回答

3

使用%, the modulus operator

var items = [1, 2, 3, 4, 5, 6, 7, 8]; 
var pos = 7; 
var threeIncrement = (pos + 3) % items.length; 
+0

謝謝您的鏈接和工作示例! – Andy