gpt4 book ai didi

javascript - 另一个对象内的对象数组(Javascript)

转载 作者:行者123 更新时间:2023-12-03 01:16:27 24 4
gpt4 key购买 nike

这里是 Javascript 的新人,试图更好地使用这种语言进行编码。所以我试图创建一个应该是 dentry 诊所的对象。在该诊所对象内,我想要一组在那里工作的所有牙医。牙医也是对象(所以对象里面有对象)。当我尝试添加/访问对象时,它们是未定义的,它告诉我它们所拥有的方法不存在。我不确定错误可能是什么,而且从我使用 Java 的时候起,我就习惯了这种方式编码。任何人都可以检查代码并指出我正确的方向吗?感谢任何帮助。

        function createDentistObject(firstName, lastName, age)
{
let dentistObject =
{
firstName: firstName, lastName: lastName, age:age,
getFullName: function()
{
return this.firstName + " " + this.lastName;
}
};
}

function createDentistList()
{
let dentistList = [(createDentistObject("Test","Test",0))];
return dentistList;
}


let myDentalClinic =
{
dentists:createDentistList(),

addDentist:function(dentistObject)
{
console.log("Dentistfullname: " + this.dentistObject.getFullName());
if(this.dentists.length == 0)
{
this.dentists.push(this.dentistObject);
}
else
{
/*if(this.dentistExist(dentistObject))
{
console.log("Dentist exists in the list!");
}*/
this.dentists.push(dentistObject);

}
},

dentistExist:function(dentistObject)
{
for(let i = 0; i < this.dentists.length; i++)
{
if(this.dentists[i].firstName === dentistObject.firstName)
{
return true;
}
}
return false;
},

printAllDentists:function()
{
let output = "";
for(let i = 0; i < this.dentists.length; i++)
{
output += this.dentists[i].firstName + "\n";
}
console.log(output);
console.log(this.dentists);
}
};


let dentistTest = createDentistObject("Dentist", "Dentiston", 38);
myDentalClinic.addDentist(dentistTest);

最佳答案

您忘记在第一个函数中返回创建的牙医对象:

function createDentistObject(firstName, lastName, age)
{
let dentistObject =
{
firstName: firstName, lastName: lastName, age:age,
getFullName: function()
{
return this.firstName + " " + this.lastName;
}
};

return dentistObject;
}

此外,您的 myDentalClinic 对象中使用 this.dentistObject 而不是您的参数 DentistObject 时存在一些拼写错误。已修复:

let myDentalClinic =
{
dentists:createDentistList(),

addDentist:function(dentistObject)
{
console.log("Dentistfullname: " + dentistObject.getFullName());
if(this.dentists.length == 0)
{
this.dentists.push(dentistObject);
}
else
{
/*if(this.dentistExist(dentistObject))
{
console.log("Dentist exists in the list!");
}*/
this.dentists.push(dentistObject);

}
},

dentistExist:function(dentistObject)
{
for(let i = 0; i < this.dentists.length; i++)
{
if(this.dentists[i].firstName === dentistObject.firstName)
{
return true;
}
}
return false;
},

printAllDentists:function()
{
let output = "";
for(let i = 0; i < this.dentists.length; i++)
{
output += this.dentists[i].firstName + "\n";
}
console.log(output);
console.log(this.dentists);
}
};

关于javascript - 另一个对象内的对象数组(Javascript),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51994393/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com