forEach 在 Javascript Class 方法中未定义

The forEach is undefined in a Javascript Class Method

我的代码有问题。在多次尝试寻找解决方案后,我决定从 Whosebug 社区获得帮助

我创建了一个 Javascript Class 用于获取注册会员列表。此会员注册已本地化到系统可以访问的 Json 文件中。

我正在尝试通过 forEach 使用数组数据过滤器。但是名为“Of(ChurchName)”的方法不会将任何 foreach 方法读入其中。当我使用 into Of() 时,returns undefined.

最初我在“createMemberList()”方法中使用了'return'响应,负责创建完整的数组。这个方法正常。但是,在 ForEach 方法的变量中使用 'return' 不起作用。然后,由于这个明显的错误,我使用了 'this' 运算符而不是 'return'。但即便如此,正如您在代码中看到的那样,我无法在“createMemberList()”中使用 forEach 方法。 有人知道吗?

详情: 我已经使用了该站点提示: https://www.techiedelight.com/copy-elements-array-into-another-array-javascript/

   const $INIT = {
        GetMembers: class{
            #listaOrdenadaItens;
            #listaMembros;
            #MemberListOfChurch;
            membersList;
            #linkGFile="LinkToJsonFileHere";
            /*Returns:
   {
         "range": "Membros!B5:AB234",
         "majorDimension": "ROWS",
         "values": [
        
            [ "",
              "",
              "",
              "",
              "",
              "",
              "",
              "",
              "",
              "",
              "",
              "",
              "",
              "",
              "",
              "",
              "",
              "",
              "",
              "",
              "",
              "",
              "",
              "",
              "",
              "",
              ""]
         ]
    }

 */
            constructor(ListFromGD){
                if(typeof ListFromGD!=="undefined"&&ListFromGD!==null){
                    this.#linkGFile=ListFromGD;
                }
                this.#createMemberList();
            }
            /*Members List*/
            Of(ChurchName){
                /**Filters member data according congregation
                 * Usage: new $INIT.GetMembers().Of("ChurchName")
                 */
                this.#MemberListOfChurch=[];;
                this.ChurchName=ChurchName;
                    
                this.membersList.forEach((item, count) => {
                 console.log("Why this code don't appears in console?");
                    if (/^[a-zA-Z_À-Úà-ú\s]{2,50}$/.test(ChurchName)==true && ChurchName.toLocaleLowerCase() == item.congregacao.toLocaleLowerCase()) {
                        
                        this.#MemberListOfChurch[count] = item;
                    }else{
                        console.log("Trys to check anyone error");
                    }
    
                }); 
                 
                return this.#MemberListOfChurch;
            }
            #getListaOrdenada (){
               return [
                   /**Personal Informations */
                   "Nome Completo",
                   "Sexo",
                   "CPF",
                   "Data de Nascimento",
                   "RG",
                   "Orgão Emissor",
                   "UF_RG",
                   "Data de Expedição",
                   "Estado Civil",
                   "CONJUGE",
                   "Naturalidade",
                   "UF_NAT",
                   "NOME_PAI",
                   "NOME_MAE",
    
                   /**Schooling and ecclesiastical data */
                   "GRAU_INSTRUCAO",
                   "PROFISSAO",
                   "FUNCAO_ECLESIASTICA",
                   "LOCAL",
                   "UF_BATISMO",
    
                   /**Address informations */
                   "Endereco",
                   "cep",
                   "bairro",
                   "cidade",
                   "uf",
                   "congregacao",
                   "contact_number",
                   "whatsapp_number"
    
               ]
            }
            #createMemberList(){
                var listaOrdenada = this.#getListaOrdenada();
    
                /**Create an array */
                var NewListMember = [];
                
                var DadosMembros={};
                /**
                 * Gets registered members list at system!
                 */
                this.#getJSON(this.#linkGFile).then(response=>{
                    response.values.forEach((item, i)=>{
                        /**Examina membro por membro aqui */
                        if(item[0]===undefined)return;

                        /**Creates a name for array of values: Ex: {"Complete Name" : "Leonardo Lima de Sousa"} */
                        listaOrdenada.forEach((ItemName,N)=>{
                            if(ItemName===undefined) return;
                            DadosMembros[ItemName]=item[N];
                        });
                        
            
                         NewListMember[i] = DadosMembros;
                         DadosMembros={};
                    });
                })
    
                this.membersList=NewListMember;
            }
    
            #getJSON=async t=>{const r=await fetch(t);if(!r.ok)throw new Error(r.statusText);return r.json()};
            
    
        }
    }

If I run this code of this function directly in the Chrome Console, it's works. But in this Class Method, returns undefined

const newArr = [...arr1, ...arr2] 会将 arr1 和 arr2 中的所有元素复制到 newArr。您不需要使用 foreach.

临时解决方案

这个问题的一个临时解决方案是将 CreateMemberList() 内容复制到 Of() 方法。此后,有必要创建一个名为 NewListMember[] 的新数组,并通过对象向其应用会众数据,其中会众名称等于 ChurchName param

Of() 方法将保持此状态:

Of(ChurchName){
            /**Filters member data according congregation
                 * Usage: new $INIT.GetMembers().Of("ChurchName")
                 */
            
            var 
                listaOrdenada   =   this.#getListaOrdenada(),
                NewListMember   =   [], 
                newArray        =   [],
                DadosMembros    =   {};
            /**
             * Gets all registered members data by Json array.
             */
            this.#getJSON(this.#linkGFile).then(response=>{
                //Creates a counter variable
                var newI=0;
                
                response.values.forEach((item, i)=>{
                    /**examines member by member here */
                    if(item[0]===undefined)return;
                    
                    /**Creates a property name for this array value: }
                      *Ex: {"Nome completo" : "Leonardo Lima de Sousa"} 
                      *     "Complete Name"
                    */
                    listaOrdenada.forEach((ItemName,N)=>{
                        if(ItemName===undefined) return;
                        DadosMembros[ItemName]=item[N];
                    });

                    //Gets current congregation name and set all letters to lowerCase()
                    var ThisCongregation        = DadosMembros.congregacao;ThisCongregation=ThisCongregation.toLowerCase();
                    
                    //Gets congregation name in to param: ChurchName and set all letters to lowerCase()
                    var CongregationIndicate    = ChurchName.toLowerCase();

                    //Gets Congregation where Congregation name is equal Param ChurchName
                    ////Then, creates a new size for array NewListMember with newI counter
                    if(ThisCongregation!==undefined&&ThisCongregation!==CongregationIndicate)return;
                     NewListMember[newI] = DadosMembros;
                     ++newI;
                     DadosMembros={};
                });
            });
            return NewListMember
        }

最终解决方案

问题出在哪里? 解决办法是什么? #createMemberList() 生成一个超过 220 行的数组。然后,需要等待 Of() 方法处理所有内容。 为此,必须在方法中使用setTimeout()函数,像这样:

setTimeout(()=>{
    console.log(JSON.stringify(this.membersList))
},3000)

代码将保持这样:

     const $INIT = {
            GetMembers: class{
                #listaOrdenadaItens;
                #listaMembros;
                #MemberListOfChurch;
                membersList;
    #linkGFile="https://cdn.jsdelivr.net/gh/OficialLeonardoLima/cdn@main/json_test.json";
         
                constructor(ListFromGD){
                    if(typeof ListFromGD!=="undefined"&&ListFromGD!==null){
                        this.#linkGFile=ListFromGD;
                    }
                    this.#createMemberList();
                  setTimeout(()=>{
                    console.log(JSON.stringify(this.membersList))
                  },3000)
                  
                  document.querySelector("#console").text=JSON.stringify(this.membersList)
                }
                /*Members List*/
                Of(ChurchName){
                    /**Filters member data according congregation
                     * Usage: new $INIT.GetMembers().Of("ChurchName")
                     */
                    this.#MemberListOfChurch=[];;
                    this.ChurchName=ChurchName;
                    
setTimeout(()=>{   
this.membersList.forEach((item, count) => {
                 console.log("Why this code don't appears in console?");
                    if (/^[a-zA-Z_À-Úà-ú\s]{2,50}$/.test(ChurchName)==true && ChurchName.toLocaleLowerCase() == item.congregacao.toLocaleLowerCase()) {
                        
                        this.#MemberListOfChurch[count] = item;
                    }else{
                        console.log("Trys to check anyone error");
                    }
    
                }); 
                                         },3000);
                     
                    return this.#MemberListOfChurch;
                }
                #getListaOrdenada (){
                   return [
                       /**Personal Informations */
                       "Nome Completo",
                       "Sexo",
                       "CPF",
                       "Data de Nascimento",
                       "RG",
                       "Orgão Emissor",
                       "UF_RG",
                       "Data de Expedição",
                       "Estado Civil",
                       "CONJUGE",
                       "Naturalidade",
                       "UF_NAT",
                       "NOME_PAI",
                       "NOME_MAE",
        
                       /**Schooling and ecclesiastical data */
                       "GRAU_INSTRUCAO",
                       "PROFISSAO",
                       "FUNCAO_ECLESIASTICA",
                       "LOCAL",
                       "UF_BATISMO",
        
                       /**Address informations */
                       "Endereco",
                       "cep",
                       "bairro",
                       "cidade",
                       "uf",
                       "congregacao",
                       "contact_number",
                       "whatsapp_number"
        
                   ]
                }
                #createMemberList(){
                    var listaOrdenada = this.#getListaOrdenada();
        
                    /**Create an array */
                    var NewListMember = [];
                    
                    var DadosMembros={};
                    /**
                     * Gets registered members list at system!
                     */
                    this.#getJSON(this.#linkGFile).then(response=>{
                        response.values.forEach((item, i)=>{
                            /**Examina membro por membro aqui */
                            if(item[0]===undefined)return;
    
                            /**Creates a name for array of values: Ex: {"Complete Name" : "Leonardo Lima de Sousa"} */
                            listaOrdenada.forEach((ItemName,N)=>{
                                if(ItemName===undefined) return;
                                DadosMembros[ItemName]=item[N];
                            });
                            
                
                             NewListMember[i] = DadosMembros;
                             DadosMembros={};
                        });
                    })
        
                    this.membersList=NewListMember;
                }
        
                #getJSON=async t=>{const r=await fetch(t);if(!r.ok)throw new Error(r.statusText);return r.json()};
                
        
            }
        }