Return 功能值无法正常工作。如何为函数 checkIfExist() 设置正确的 return 值?

Return value for function is not working correctly. How to set up correct return value for function checkIfExist()?

我正在为 Premiere pro 编写一个脚本,我可以在其中添加时间轴中的标记并一次性为每个标记导出静止图像。但是,当我编写一个函数来检查以前是否创建过静止图像时,函数告诉我它找到了先前创建的静止图像,但仍然创建了一个新的静止图像。 所以基本上:Function returns 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;
}

我认为这是因为你的递归:

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

如果在 return 为真之前启动此功能,您将再次 运行 该功能。

现在第一个 运行 可以 return 为真,而第二个(甚至第三个或第四个等)可以 return 为假,从而创建一个新的,同时也找到了。

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

但这不适用于嵌套数组。然后你需要创建另一个函数来首先创建一个包含所有嵌套数组的平面副本,然后再执行 arr.find 或 arr.find 索引。仍然认为这是更好的解决方案。

您可以使用它来将嵌套数组变成一个平面数组:

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]