0

適応させたコードを使用していますが、最善の方法がよくわかりません。リスト項目の配列に特定の値の並べ替えを適用するさまざまな並べ替え関数を使用して、少しのコードを合理化しようとしています。

現時点では、関数は特定の要因に基づいて比較を行い、ソートする値を返します。

この配列/ソート呼び出しで 2 つの追加変数を渡したいのですが、これを記述する方法がうまくいかないようです。現時点では、ウィンドウにグローバル変数を配置するという厄介な方法でそれを行っていますが、変数を直接渡したいと思っています。

以下のコードに基づいて、それを締めてクリーンアップする方法をいただければ幸いです。

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;
  }
}
4

2 に答える 2

1

いくつの要素があるかはわかりませんが$j、コンパレーター関数内でこれらの jQuery 呼び出しを行わないようにすれば (それがそうであると仮定して)、速度が向上します。

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;
于 2013-08-26T15:50:26.773 に答える
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));
}
于 2013-08-26T15:41:33.550 に答える