Javascript - 使用数组传递变量

时间:2013-08-26 15:34:58

标签: javascript jquery arrays performance sorting

我正在处理一些我改编自的代码,并且我不太了解最好的方法。我正在尝试使用不同的排序函数来简化一些代码,这些函数将特定值的排序应用于列表项数组。

此时,函数根据特定因子进行比较,然后返回值进行排序。

我想通过这个数组/排序调用传递两个额外的变量,但我似乎无法解决这个问题。目前我通过在窗口上设置全局变量以令人讨厌的方式进行此操作,但我宁愿直接传递变量。

根据以下代码,任何收紧&的方法清理它将不胜感激:

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

2 个答案:

答案 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 :(得分: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;
相关问题