【问题标题】:Return value for function is not working correctly. How to set up correct return value for function checkIfExist()?函数的返回值无法正常工作。如何为函数 checkIfExist() 设置正确的返回值?
【发布时间】:2019-08-13 14:13:55
【问题描述】:

我正在为 Premiere pro 编写一个脚本,我可以在时间轴中添加标记并一次性导出每个标记的静止图像。但是,当我编写一个函数来检查之前是否已经创建了静止图像时,这些函数告诉我它找到了以前创建的静止图像,但仍然创建了一个新的静止图像。 所以基本上:函数返回 true,但仍然执行 else{}

    //checks if the frame that is about to be exported already exists 
        if(checkIfExist(app.project.rootItem, outputFile)){
            alert("frame already exists");
        }else{
        //This is where the actual still gets created and imported
            activeSequence.exportFramePNG(time, outputFileName);
        //here the previously created item gets moved to the appropriate bin (This is working great ATM)
            moveToBin(outputFile);
       }
    }
}
//This function is meant to check if an item exists in the project bin. It does this by looping though all the items in the array from the start. 
function checkIfExist(currentItem, name){
    for(var i = 0; i<currentItem.children.numItems; i++){
        currentChild = currentItem.children[i];
        if(currentChild.name.toUpperCase() === name.toUpperCase()){
            alert("Found:   " + currentChild.name);
            return true;
        }if(currentChild.type == ProjectItemType.BIN){
            checkIfExist(currentChild, name);
        }
    }
    return false;
}

【问题讨论】:

  • checkIfExist 运行的次数很可能超过了您认为它运行的次数。这是真的,但随后再次运行它是错误的,然后你的 else 也运行了
  • 感谢您的回复。我如何检查是否可以?如果是这样,我该如何解决?
  • 您可以通过在函数内部放置一个 console.log 来检查它是否记录了不止一次。也许还可以在函数中添加一个 if 语句。下面我的答案中可能的解决方案

标签: javascript extendscript adobe-premiere


【解决方案1】:

我认为这是因为您执行递归:

 if(currentChild.type == ProjectItemType.BIN){
            checkIfExist(currentChild, name);
 }

如果这个函数在你返回 true 之前就被启动了,你将开始第二次运行这个函数。

现在第一次运行可以返回 true,而第二次(甚至是第 3 次或第 4 次等)可以返回 false,从而创建一个新的,同时也找到它。

如果可能,请尝试使用 arr.find 或 arr.findIndex 并检查值是否为 -1(或未找到)。这将使您的代码更短、更简洁、更容易出错:)

但这不适用于嵌套数组。然后,在执行 arr.find 或 arr.findIndex 之前,您需要先创建一个包含所有嵌套数组的平面副本。仍然认为这是更好的解决方案。

你可以用它把嵌套数组变成一个平面数组:

let arr1 = [1,2,3,[1,2,3,4, [2,3,4]]];

function flattenDeep(arr1) {
   return arr1.reduce((acc, val) => Array.isArray(val) ? acc.concat(flattenDeep(val)) : acc.concat(val), []);
}
flattenDeep(arr1);// [1, 2, 3, 1, 2, 3, 4, 2, 3, 4]

【讨论】:

  • 好主意!将def尝试。我会告诉你它是否有效。
  • 抱歉编辑,我自己有点困惑;)但我认为递归是给你描述的麻烦的事情。
  • 感谢您的回复。我确实取得了一些进展。然而,事实证明 .find 和 .findIndex 没有在 Extendscript 中实现。来自 Adob​​e 论坛:“其中一些功能不存在的主要原因是,ExtendScript 基于 ECMA-262 标准。非常古老的 Javascript,我相信并非所有功能都已实现。”
猜你喜欢
  • 1970-01-01
  • 2018-02-07
  • 1970-01-01
  • 2017-08-22
  • 2011-10-29
  • 2016-03-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多