2010-06-23 47 views
1

首先返回值的範圍,道歉,這應該是簡單的,但我已經有太多太多的咖啡和不能完成我疲倦的大腦解決這個(至少在沒有使它的方式更比我知道它應該是複雜的)。給定一個指標,從陣列

可以說我有在這一個簡單的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的:)

回答

1

編輯:(刪除原來的版本,因爲它是比這更廢話)

function getBatch(items, start) { 
    var tmpArr = items; 
    tmpArr.splice(0,0,items); 

    var offset = (start > items.length-3) ? 0 : items.length; 

    return tmpArr.slice(start+offset-1,start+offset+3); 
} 

編輯2.1(bugfixed)

編輯2.2(移動開始實際的開始和消除一個包裝盒(最終)

好吧,哭泣的男孩照顧他的母親,現在,讓我們這樣做是正確的

function getBatch(items, start) { 
    // Behaviour not defined by example 
    if(items.length < 4) 
    return items; 

    // Set start to actual start (start-1), and 
    // ensure that start is always within 0 - items.length 
    start = ((start-1)+items.length) % items.length; 

    // First take care of the easy case. 
    if(start < items.length-3) return items.slice(start,start+4); 

    // Last x elements + (4-x) elements from beginning of array 
    return items.slice(start).concat(items.slice(0,4-(items.length-start))); 
} 
+0

不錯,但這並不能滿足所有情況。提供一個0的起始值將返回一個空數組。 (items.length-1)的起始值返回[「in」,「it」] – donohoe 2010-06-23 16:11:44

+0

現在應該更好了...... – 2010-06-23 16:45:19

+0

使用你的第二次編輯作爲突破,我可以使用這個工作版本(格式不正確):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

3

好答案,顯然是幼稚的第一步是簡單地寫

return items.slice(start - 1, start + 2) 

但是這不會與您需要的包裝工作。應工作的一種方法是一個輔助功能,有效地使上兩邊的陣列圓形:

function getElementAtIndex(items, idx) { 
    // Normalise the index to an element in the actual range 
    while (idx > items.length - 1) 
    { 
     idx -= items.length; 
    } 
    while (idx < 0) 
    { 
     idx += items.length; 
    } 

    return items[idx]; 
} 

然後,你可以簡單地手動返回四個要素周圍索引像這樣:

function getBatch(items, start) { 
    return [ getElementAtIndex(items, start - 1), 
      getElementAtIndex(items, start), 
      getElementAtIndex(items, start + 1), 
      getElementAtIndex(items, start + 2)]; 
} 

這種方法顯示正在工作here

這可能不是最高效或優雅的方法,但理解和實現起來相當直接,所以如果此代碼不在性能熱點中,它可能最終成爲最實用的方法。