不使用 let javascript 重写代码

Rewrite code without using let javascript

假设变量的重新分配会导致难以调试的错误,我正在寻找不在此示例中使用 let 的选项。请指教

function getNodeById<F extends ISomeOptions>(
   optionsList: F[],
   nodeId: string): F | null {

   let result: ISomeOptions | null = null;

   optionsList.forEach((node) => {
     if (node.id === nodeId) {
       return (result = node);
     }

     if (
       Array.isArray(node.children) &&
       getNodeById(node.children, nodeId)
     ) {
       return (result = getNodeById(node.children, nodeId));
     }

     return null;
   });

   return result;
 }

您可以使用Array.find

function getNodeById<F extends ISomeOptions>(
   optionsList: F[],
   nodeId: string): F | null {

   return optionsList.find((node) => {
      if (node.id === nodeId) return node
      if (Array.isArray(node.children) {
         // getNodeById is a recursive function, so it could be expensive to run it twice.
         let child = getNodeById(node.children, nodeId)
         if (child) return child
      }
   });

   return result;
 }

你想要一个简单的循环,你可以立即 return 而不是 forEach:

function getNodeById<F extends ISomeOptions>(
   optionsList: F[],
   nodeId: string): F | null {

   for (const node of optionsList) {
     if (node.id === nodeId) {
       return node;
     }

     if (Array.isArray(node.children)) {
       const node1 = getNodeById(node.children, nodeId);
       if (node1) {
         return node1;
       }
     }
   }

   return null;
 }