字符串替换函数没有响应

String replace function isnt responding

本文关键字:响应 函数 替换 字符串      更新时间:2023-09-26

我正在用JS编写一个photoshop脚本,此时我要求用户选择和文件夹位置并将所有这些文件添加到数组中。然后我希望解析数组,以便只保留文件名。

我收到此错误:文件列表[i].replace 不是一个函数

我想这是由于我传入了错误的值或使用错误的类型。希望有人能解释这个问题并帮助我解决它吗?

//Prompt for folder location
var Path = Folder.selectDialog("Select Folder Location for Renders")
// Use the path to the application and append the samples folder 
var samplesFolder = Folder(Path)
var fileList = samplesFolder.getFiles()
for (var i = 0; i < fileList.length; i++)
{
    fileList[i] = fileList[i].replace(/^.*['''/]/, '')
} 
prompt("Complete")

谢谢你的时间,AtB

S

发生错误是因为您需要一个字符串,但它不是一个字符串。

http://jongware.mit.edu/idcs5js_html_3.0.3i/idcs5js/pc_Folder.html 说getFiles

返回

文件和文件夹对象的数组,如果此对象的引用文件夹不存在,则返回 null。

幸运的是,FileFolder都具有以下属性:

  • fsName - 引用文件的特定于平台的完整路径名
  • fullName - 引用的文件的完整路径名,采用 URI 表示法。
  • name - 引用文件的绝对 URI 的文件名部分,不带路径规范

当然,如果您不想要任何路径,而只想要文件名,请使用 name ,否则,请在适合您的任何命令上使用 replace 命令 - fsNamefullName .

所以 - 在你的循环中,你想要:

fileList[i] = fileList[i].name

您可能希望在最终结果中过滤掉文件夹。 这将在你的循环中需要这样的东西:

if (fileList[i] instanceof Folder) {
    fileList.splice(i, 1);
    --i; // go back one i, because you just removed an index.  Note, if you're not careful, such shenanigans may mess up the second term of the for loop.
    continue;
}

最后一个建议:我个人认为制作一个新数组比在原地进行替换更干净。 该语言当然支持您正在做的事情,但它仍然让我抽搐着从File or Folder arraystring array。 (当然,你认为你正在做字符串数组到字符串数组。 这也将简化删除文件夹索引等的任何问题。