我需要硬编码一个简单的 foreach 函数,该函数 console.logs 会从数组中输出具有相同值的特定属性的对象列表。但console.log一直显示未定义。我不知道我在这里做错了什么。是否定义了导致问题的类?如果我只需要处理类,我该如何解决这个问题?
class Hive {
constructor(apiary_name, hive_name, hive_number) {
this.apiary_name = apiary_name;
this.hive_name = hive_name;
this.hive_number = hive_number;
}}
const Hive1_A1 = new Hive(A1, 'My First Hive in A1', 1111)
const Hive2_A1 = new Hive(A1, 'My Second Hive in A1', 2222)
const Hive3_A1 = new Hive(A1, 'My Third Hive in A1', 3333)
const Hive1_A2 = new Hive(A2, 'My First Hive in A2', 1111)
const Hive2_A2 = new Hive(A2, 'My Second Hive in A2', 2222)
const Hive3_A2 = new Hive(A2, 'My Third Hive in A2', 3333)
const Hives = [
{Hive1_A1},{Hive2_A1},{Hive3_A1},{Hive1_A2},{Hive2_A2},{Hive3_A2},
]
function listHives(ApiaryName_Hive_1){
var hives = Hives;
hives.forEach((hive) => {
if(hive.apiary_name === ApiaryName_Hive_1) {
console.log(hive);
} else {
console.log('No hives in apiary A1 can be found')
}
});
}
listHives('A1')
通过调用函数 listHives('A1'),我希望在 console.log 中仅看到列出的 Hive_1_A1、Hive_2_A1、Hive_3_A1。
最佳答案
当你这样做时:
const Hives = [
{Hive1_A1},{Hive2_A1},{Hive3_A1},{Hive1_A2},{Hive2_A2},{Hive3_A2},
]
您正在使用创建对象的 JS 简写。这将为您提供一个对象列表,例如:
[{Hive1_A1: Hive1_A1}, {Hive2_A1: Hive2_A1} ...]
如果您只想要一个可以迭代的 Hive 列表,请不要在列表定义中使用 {}
,只需创建一个普通数组即可:
const Hives = [Hive1_A1, Hive2_A1, Hive3_A1...]
class Hive {
constructor(apiary_name, hive_name, hive_number) {
this.apiary_name = apiary_name;
this.hive_name = hive_name;
this.hive_number = hive_number;
}}
const Hive1_A1 = new Hive("A1", 'My First Hive in A1', 1111)
const Hive2_A1 = new Hive("A1", 'My Second Hive in A1', 2222)
const Hive3_A1 = new Hive("A1", 'My Third Hive in A1', 3333)
const Hive1_A2 = new Hive("A2", 'My First Hive in A2', 1111)
const Hive2_A2 = new Hive("A2", 'My Second Hive in A2', 2222)
const Hive3_A2 = new Hive("A2", 'My Third Hive in A2', 3333)
const Hives = [Hive1_A1, Hive2_A1, Hive3_A1, Hive1_A2, Hive2_A2, Hive3_A2]
function listHives(ApiaryName_Hive_1){
var hives = Hives;
hives.forEach((hive) => {
if(hive.apiary_name === ApiaryName_Hive_1) {
console.log(hive);
} else {
console.log('No hives in apiary A1 can be found')
}
});
}
listHives('A1')
关于javascript - 如何从数组中获取分类对象的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56064479/