首页 > 解决方案 > 运行reduce,map函数

问题描述

我在 country.json 中有 3 个类和数据

国家.json

[{"country":"Algeria","region":"Northern Africa","code":"DZ","population":41318142,"cities":["Boumerdas","Zeribet el Oued","Zeralda"]},{"country":"American Samoa","region":"Polynesia","code":"AS","population":55641,"cities":["Aūa","Vaitogi","Vailoatai"]}

在 countryRep 类中,我使用这个函数来获取人口总和

   async  getSumAllPopulation(){
            let countries = await this.getCountries();
           let populations= countries.map(s=>s.population).reduce((acc, s) => s + acc);
           return populations;
        }

在测试中我写

app.get('/PopulationSum', async (req, res) => {
    const countries = await repo.getSumAllPopulation();
    res.send(countries);
})

getCountries() 函数

    async getCountries() {
        try {
            const countries = await fs.readJSON(this.countryFilePath);
            return countries;
        }
        catch (e) {
            console.log(e)
        }

    }

但是我没有得到 sum 的结果?我该如何解决?我收到一个错误,似乎该方法没有返回任何东西。

在此处输入图像描述

标签: javascriptdictionary

解决方案


推荐阅读