2012-06-04 12 views
3

我正在編寫Backbone.Collection的規範。
我想檢查下面的語句中使用的javascript茉莉一個單元測試:我應該如何檢查茉莉花或JavaScript中的排序語句

should the models be ordered by starting with the most recent. 

在模型來檢查關鍵值是id(這是一個整數)。

[ 
{id: 5, ….}, // the most recent 
{id: 2, ...}, 
{id: 1, ...} 
] 

我的問題是:
1)是否有茉莉花方法,使這種檢查的

例如,如果它看起來像這樣的集合進行排序?
2)如果沒有,在javascript中使用它的最好方法是什麼?也許使用一些庫,如下劃線。

+0

你想檢查是否一個對象數組是按其ID來排序的? –

+0

@SiGanteng是的,你明白了。我想檢查對象數組是否按id排序 –

回答

2

你可以for循環做了,如果不知道有內置,檢查你想要什麼:

var max = arr[0].id; 
    var sorted = true; 

    for(var i = 1; i < arr.length; i++) { 
     if(max > arr[i].id) { 
      sorted = false; break; 
     } 
    } 

    alert(sorted); 
0

據推測,您的集合comparator,將讓您的收藏分類在已設置。

在您的測試,創建3個項目無序,讓我們說:

collection = new MyCollection(); 
collection.add({id: 1, bar: 'foo1'}); 
collection.add({id: 5, bar: 'foo5'}); 
collection.add({id: 3, bar: 'foo3'}); 

然後確保比較的作品,變得那麼容易,因爲:

expect(_.pluck(collection.models, 'id')).toEqual([5, 3, 1]);