返回值返回为未定义

时间:2019-07-16 13:23:18

标签: javascript adobe return-value adobe-illustrator object-literal

我正在尝试为Illustrator编写脚本,该脚本将从对象中读取所需的颜色,然后在需要的位置用该颜色填充模板。它不断返回未定义状态。我对Javascript陌生,我有什么想法我做错了吗?

我尝试返回newCMYKColor[stockColor]newCMYKColor[stockColors]并返回stockColor[newCMYKColor]

convertRoofColorToCMYK = function(stockColor) {
  var newCMYKColor = new CMYKColor(),
    stockColors = {
      BlackPoly: [80, 72, 68, 100],
      LightBlue: [100, 43, 0, 30],
      DarkBluePoly: [95, 74, 7, 44],
      PurplePoly: [82, 98, 0, 12],
      GreenPoly: [90, 12, 95, 40],
      YellowPoly: [0, 19, 89, 0],
      EcruPoly: [6, 13, 41, 4],
      OrangePoly: [0, 73, 98, 0],
      RedPoly: [7, 100, 82, 26],
      GreyPoly: [10, 4, 4, 14],
      WhitePoly: [0, 0, 0, 0]
    };
  try {
    newCMYKColor.cyan = stockColors[stockColor][0];
    newCMYKColor.magenta = stockColors[stockColor][1];
    newCMYKColor.yellow = stockColors[stockColor][2];
    newCMYKColor.black = stockColors[stockColor][3];
  } catch (e) {
    newCMYKColor.cyan = 0;
    newCMYKColor.magenta = 0;
    newCMYKColor.yellow = 0;
    newCMYKColor.black = 0;
  }
  return newCMYKColor;
};

roofColorCMYK = convertRoofColorToCMYK(Clipboard.roof_color);

if (!roofColorCMYK == undefined) {
  if (app.activeDocument.Layers["Tent Pieces"] &&
    app.activeDocument.Layers["Tent Pieces"].Layers["Roof Composite"]) {
    for (i = 0; i < app.activeDocument.Layers["Tent Pieces"].Layers["Roof Composite"].pathItems.length; i++) {
      app.activeDocument.Layers["Tent Pieces"].Layers["Roof Composite"].pathItems[i].fillColor = roofColorCMYK;
    } else {
      alert("sorry we are not able to fill the tent roof with the " +
        Clipboard.roof_color + " color.")
    }

在添加else / if语句之前,它是在if (app.activeDocument.Layers["Tent Pieces"] && app.activeDocument.Layers["Tent Pieces"].Layers["Roof Composite"])告诉我未定义的。添加else / if语句后,它每次都会向我发出警报。

1 个答案:

答案 0 :(得分:1)

请查看有关“尝试捕获”块的MDN规范。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/try...catch

您必须记住,在try catch块之后将不执行任何代码。

我建议您以这种方式更改代码:

try {
    newCMYKColor.cyan = stockColors[stockColor][0];
    newCMYKColor.magenta = stockColors[stockColor][1];
    newCMYKColor.yellow = stockColors[stockColor][2];
    newCMYKColor.black = stockColors[stockColor][3];

    return newCMYKColor;
  } catch (e) {
    newCMYKColor.cyan = 0;
    newCMYKColor.magenta = 0;
    newCMYKColor.yellow = 0;
    newCMYKColor.black = 0;

    return newCMYKColor;
  }

或在末尾使用finally块(finally内部的代码始终会执行之前发生的一切)。

try {
    newCMYKColor.cyan = stockColors[stockColor][0];
    newCMYKColor.magenta = stockColors[stockColor][1];
    newCMYKColor.yellow = stockColors[stockColor][2];
    newCMYKColor.black = stockColors[stockColor][3];
  } catch (e) {
    newCMYKColor.cyan = 0;
    newCMYKColor.magenta = 0;
    newCMYKColor.yellow = 0;
    newCMYKColor.black = 0;
  } finaly {
    return newCMYKColor;
  }