如何在Indesign脚本中使用像Array.reduce()这样的高阶函数?

时间:2016-02-08 17:51:57

标签: javascript arrays adobe-indesign extendscript

我已经启动了一个项目,我需要使用Adobe Indesign和ExtendScript以编程方式从一系列INDD文件中提取一些数据。在这些程序中用于编写脚本的Javascript版本不支持我以前使用的任何高阶函数(Array.reduce()Array.forEach()Array.map(),等...)。

有没有办法将此功能添加到ExtendScript?我觉得我在四英尺高的天花板上走来走去。

2 个答案:

答案 0 :(得分:6)

使用Polyfill

ExtendScript似乎支持纯Javascript对象的原型设计(但not Indesign DOM objects),因此可以使用polyfill添加缺少的功能。可以在页面上的MDN上找到Polyfill代码,用于" Polyfill"中所讨论的方法。这是一个例子:MDN Array.prototype.reduce() Polyfill。有多种方法可以使用填充,包括Array.map()Array.indexOf()Array.filter()Array.forEach()

要实现代码,只需在与脚本相同的文件夹中创建一个适当命名的文件(即polyfill.jsreduce.js)。将填充代码从MDN复制到刚刚创建的文件中,如下所示:

// Production steps of ECMA-262, Edition 5, 15.4.4.21
// Reference: http://es5.github.io/#x15.4.4.21
if (!Array.prototype.reduce) {
  Array.prototype.reduce = function(callback /*, initialValue*/) {
    'use strict';
    if (this == null) {
      throw new TypeError('Array.prototype.reduce called on null or undefined');
    }
    if (typeof callback !== 'function') {
      throw new TypeError(callback + ' is not a function');
    }
    var t = Object(this), len = t.length >>> 0, k = 0, value;
    if (arguments.length == 2) {
      value = arguments[1];
    } else {
      while (k < len && !(k in t)) {
        k++; 
      }
      if (k >= len) {
        throw new TypeError('Reduce of empty array with no initial value');
      }
      value = t[k++];
    }
    for (; k < len; k++) {
      if (k in t) {
        value = callback(value, t[k], k, t);
      }
    }
    return value;
  };
}

然后在脚本开头添加以下行,相应地替换文件名:

#include 'polyfill.js';

该行末尾的分号并未包含在Adobe文档中,但我发现有时ExtendScript会因错误而抛出错误,特别是如果您正在使用{{1 \ n}多次。

答案 1 :(得分:2)

我使用underscore.js代替。

Underscore.js http://underscorejs.org/

#include '/path-to/underscore.js'
var _ = this._;

在脚本开头添加此代码段。

谢谢

毫克

相关问题