我需要硬编码一个简单的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列表。
发布于 2019-05-09 17:18:51
当你这样做时:
const Hives = [
{Hive1_A1},{Hive2_A1},{Hive3_A1},{Hive1_A2},{Hive2_A2},{Hive3_A2},
]您正在使用创建对象的JS速记。这给出了如下对象的列表:
[{Hive1_A1: Hive1_A1}, {Hive2_A1: Hive2_A1} ...]如果您只想要一个可以迭代的Hives列表,不要在列表定义中使用{},只需创建一个简单的数组:
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')
https://stackoverflow.com/questions/56064479
复制相似问题