2013-08-26 41 views
0

我正在處理一些我改編自的代碼,還有一些我不太明白最好的方法。我試圖用不同的排序函數簡化一些代碼,這些排序函數將特定值的排序應用於列表項的數組。Javascript - 用數組傳遞變量

此刻,函數根據特定因子進行比較,然後返回值進行排序。

我想通過這個數組/排序調用傳遞兩個額外的變量,但我似乎無法解決寫這個問題的方法。目前,我通過在窗口中添加全局變量來以惡意的方式執行此操作,但我寧願直接傳遞變量。

基於下面的代碼,任何方式收緊&把它清理乾淨,將不勝感激:

arr = []; 
sort_func = $j(this).children(':selected').val(); 

$j('li.collectionItem').each(function(){ 
    arr.push(this); 
}); 

if (sort_func == "a_z") 
{ 
     window.dataType = 'alpha'; 
     window.bigFirst = false; 
     arr.sort(sort_products); 
} 
else if (sort_func == "z_a") 
{ 
     window.dataType = 'alpha'; 
     window.bigFirst = true; 
     arr.sort(sort_products); 
} 


// custom sort functions 
function sort_products(a, b) 
{ 
    dataType = window.dataType; 
    bigFirst = window.bigFirst; 

    var compA = $j(a).data(dataType); 
    var compB = $j(b).data(dataType); 

    if (bigFirst == true) 
    { 
    return (compA > compB) ? -1 : (compA < compB) ? 1 : 0; 
    } 
    else 
    { 
    return (compA < compB) ? -1 : (compA > compB) ? 1 : 0; 
    } 
} 

回答

1

您可以在另一個函數包原sort_products,像這樣:

function sort_products(dataType, bigFirst) 
{ 
    return function (a, b) 
    { 
    var compA = $j(a).data(dataType); 
    var compB = $j(b).data(dataType); 

    if (bigFirst == true) 
    { 
     return (compA > compB) ? -1 : (compA < compB) ? 1 : 0; 
    } 
    else 
    { 
     return (compA < compB) ? -1 : (compA > compB) ? 1 : 0; 
    } 
    } 
} 

然後你可以這樣使用它:

if (sort_func == "a_z") 
{ 
    arr.sort(sort_products('alpha', false)); 
} 
else if (sort_func == "z_a") 
{ 
    arr.sort(sort_products('alpha', true)); 
} 
1

我不知道你有多少元素,但如果你避免在比較函數中調用那些jQuery(假設這就是$j),它會加快速度。

var arr = []; // You really need to declare your variables! 
var sort_func = $j(this).children(':selected').val(); 
var sortInfo = { 
    'a_z': {type: 'alpha', ascending: true}, 
    'z_a': {type: 'alpha', ascending: false}, 
    // ... whatever the other types are 
}[sort_func]; 

$j('li.collectionItem').each(function(){ 
    arr.push({ elem: this, key: $j(this).data(sortInfo.type) }); 
}); 

arr.sort(function(a, b) { 
    return (sortInfo.ascending ? 1 : -1) * 
    a.key > b.key ? 1 : a.key < b.key ? -1 : 0; 
}); 

// transform the array into an array of just the DOM nodes 
for (var i = 0; i < arr.length; ++i) 
    arr[i] = arr[i].elem; 
+0

感謝隊友,好東西在這裏。同意範圍變量。出於興趣,這是速度還是合規性問題? –

+1

@LetterAfterZ好,它主要是表現。比較例程將被調用很多次,所以儘可能便宜使得較大的列表有所不同。 – Pointy