【问题标题】:How do I get the value of a classed object from an array如何从数组中获取分类对象的值
【发布时间】: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


    【解决方案1】:

    当你这样做时:

    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')

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-17
      • 2021-02-07
      • 2019-09-19
      • 1970-01-01
      相关资源
      最近更新 更多