带有参数的函数反向循环

时间:2015-07-10 20:15:56

标签: javascript function for-loop photoshop-script

在JavaScript中有没有办法将参数传递给函数,以便它反转循环的方向?

var srcDoc = app.activeDocument;
var str = "";

// iterateLayers(srcDoc, true); // 3 2 1 0
iterateLayers(srcDoc, false);  // 0 1 2 3

function iterateLayers(srcDoc, rev)
{
  var numOfLayers = sauce.layers.length;
  if (rev)
  {
    for (var i = numOfLayers -1; i >= 0; i--)
    {
      str+= i + " ";
    }
  }
  else
  {
    for (var i = 0; i < numOfLayers; i++)
    {
      str+= i + " ";
    }
  }
}

alert(str); 

1 个答案:

答案 0 :(得分:1)

HA!我用三元运算符解决了这个问题。去吧!

// call the source document
var srcDoc = app.activeDocument;

var str = "";

// iterateLayers(srcDoc, true); // 3 2 1 0
iterateLayers(srcDoc, false);  // 0 1 2 3

function iterateLayers(sauce, rev)
{
  var numOfLayers = sauce.layers.length;
  for (var i = numOfLayers -1; i >= 0; i--)
  {
    var index = (rev == true) ?  i : (sauce.layers.length-i)-1;
    str+= index + " ";
  }
}

alert(str);