[英]The forEach is undefined in a Javascript Class Method
I are have a problem into my code.我的代码有问题。 After many attempts in search for solutions I decided to get help from the stackoverflow community
经过多次尝试寻找解决方案后,我决定从 stackoverflow 社区获得帮助
I have created a Javascript Class for get registered members list.我创建了一个 Javascript 类来获取注册成员列表。 This members register is localized in to a Json file which system have access.
该成员寄存器被本地化为系统可以访问的 Json 文件。
I'm trying to use an array data filter through forEach.我正在尝试通过 forEach 使用数组数据过滤器。 But the method named: "Of(ChurchName)" don't read any foreach method into it.
但是名为“Of(ChurchName)”的方法不会将任何 foreach 方法读入其中。 When I using into Of(), returns undefined.
当我使用 into Of() 时,返回未定义。
Initially I used 'return' response in the method "createMemberList()", responsible to create the full array.最初我在方法“createMemberList()”中使用了“return”响应,负责创建完整的数组。 This method it's working normally.
这种方法可以正常工作。 But, using 'return' in a variable with ForEach method not work.
但是,使用 ForEach 方法在变量中使用“return”不起作用。 Then, because this aparent error, I has used the 'this' operator instead of 'return'.
然后,因为这个明显的错误,我使用了“this”运算符而不是“return”。 But even so, as can you see in code, i can't use the forEach method at "createMemberList()".
但即便如此,正如您在代码中看到的那样,我不能在“createMemberList()”处使用 forEach 方法。 Does anyone has any idea?
有人知道吗?
Details: I aredy used that site tips: https://www.techiedelight.com/copy-elements-array-into-another-array-javascript/详细信息:我已使用该站点提示: 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.
如果我直接在 Chrome 控制台中运行此功能的代码,它就可以工作。 But in this Class Method, returns undefined
但是在这个类方法中,返回未定义
const newArr = [...arr1, ...arr2]
will copy all the elements from arr1 and arr2 to newArr. const newArr = [...arr1, ...arr2]
会将 arr1 和 arr2 中的所有元素复制到 newArr。 You don't need to use foreach
.您不需要使用
foreach
。
TEMPORARY SOLUTION临时解决方案
A temporary solution for this problem is copy CreateMemberList()
content to Of()
Method.这个问题的一个临时解决方案是将
CreateMemberList()
内容复制到Of()
方法。 Thereafter, It's necessary create a new Array named NewListMember[] and apply congregations data via objects to it where congregation name is equal ChurchName param此后,有必要创建一个名为 NewListMember[] 的新数组,并通过对象应用会众数据,其中会众名称等于 ChurchName 参数
The Of()
Method will be staying this: 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
}
where were problem?哪里出了问题? What's solution?
有什么解决办法? The
#createMemberList()
generate an array with more than 220 rows. #createMemberList()
生成一个超过 220 行的数组。 Then, it's necessary wait a while for Of()
method to process everything.然后,需要等待一段时间让
Of()
方法处理所有内容。 For it, it's must to use setTimeout()
function in the method, like this:为此,必须在方法中使用
setTimeout()
函数,如下所示:
setTimeout(()=>{
console.log(JSON.stringify(this.membersList))
},3000)
The code will to stay like this:代码将保持这样:
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()};
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.