首先返回值的範圍,道歉,這應該是簡單的,但我已經有太多太多的咖啡和不能完成我疲倦的大腦解決這個(至少在沒有使它的方式更比我知道它應該是複雜的)。給定一個指標,從陣列
可以說我有在這一個簡單的Javascript數組了一些項目:
var items = ["Hello", "This", "is", "an", "array", "with",
"a", "number", "of", "items", "in", "it"];
無論出於何種原因,我在第二個值突然感興趣:
items[1]
//-> "This"
但我也想要得到的前值,而接下來的兩個值...
//-> "Hello", "This", "is", "an"
要這樣說:
function getBatch(items, start) {
// What goes here so it would return the results below?
}
getBatch(items, 0);
//-> ["it", "Hello", "This", "is"]
getBatch(items, 4);
//-> ["an", "array", "with", "a"]
getBatch(items, (items.length-1));
//-> ["in" "it", "Hello", "This"]
函數getBatch
(上面)爲了返回這些結果集的代碼是什麼?
請,不依賴於JQuery的:)
不錯,但這並不能滿足所有情況。提供一個0的起始值將返回一個空數組。 (items.length-1)的起始值返回[「in」,「it」] – donohoe 2010-06-23 16:11:44
現在應該更好了...... – 2010-06-23 16:45:19
使用你的第二次編輯作爲突破,我可以使用這個工作版本(格式不正確):function getBatch(items,start){var tmpArr = items; if(start == 0)//將最後一個元素添加到數組的開頭(如第一個示例所定義的) tmpArr.splice(0,0,tmpArr.slice(-1).toString()); start = 1; (開始>項目長度-3)tmpArr = tmpArr.concat(tmpArr,tmpArr.slice(0,2));否則如果(開始>項目長度-3)tmpArr = tmpArr.concat(tmpArr,tmpArr.slice(0,2)); } return tmpArr.slice(start-1,start + 3); } – donohoe 2010-06-23 16:52:02