【发布时间】:2019-09-27 14:07:31
【问题描述】:
我需要硬编码一个简单的 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 列出。
【问题讨论】:
标签: javascript arrays class object foreach