gpt4 book ai didi

javascript - 如何在 Indesign 脚本中使用 Array.reduce() 等高阶函数?

转载 作者:数据小太阳 更新时间:2023-10-29 06:01:07 24 4
gpt4 key购买 nike

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

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

最佳答案

使用 Polyfill

ExtendScript 似乎支持纯 Javascript 对象的原型(prototype)设计(但 not Indesign DOM objects ),因此可以使用 polyfill 来添加缺失的功能。 Polyfill 代码可以在 MDN 上的“Polyfill”下的相关方法页面上找到。这是一个例子:MDN Array.prototype.reduce() Polyfill .有许多方法的 polyfill,包括 Array.map()Array.indexOf()Array.filter()Array.forEach().

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

// 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';

行尾的分号没有包含在 Adob​​e 文档中,但我发现如果不加分号,有时 ExtendScript 会抛出错误,尤其是当您多次使用 #include 时.

关于javascript - 如何在 Indesign 脚本中使用 Array.reduce() 等高阶函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35276076/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com