在 JavaScript 中使用解构的正确方法

Correct way to use destructuring in JavaScript

我从数据库中获取数据,我只需要两个数组。使用两个变量,我得到了我需要的结果,但我明白,这段代码写得不正确。甚至 npm 也写了箭头函数应该 return 东西,所以我添加了 "return false";

let flagUrls = [];
let countryNames = [];

country.map((country, index) => {
   flagUrls[index] = country.flagUrls;
   countryNames[index] = country.countryNames;
   return false;
});

this.setState({ flagUrls, countryNames });

我这样试过:

let flagsAndCountrys =  country.map((country, index) =>[country.flagUrls, country.countryNames])


this.setState({ 
   flagsAndCountrys.flagUrls,
   flagsAndCountrys.countryNames 
   });

map方法使用调用数组中每个元素上提供的函数的 return 值创建一个新数组。
请注意上面一行中的 return 一词。您需要 return 一些将被插入到新数组中的东西。

因此,使用 map 您可以创建一个新数组,其中包含仅具有 flagUrlscountryNames 字段的对象,如下所示:

let result = country.map((country, index) => {
   return {
     flagUrl: country.flagUrls,
     countryName: country.countryNames
   }
});

如果您想维护两个 flagUrls 和 countryNames 数组,则不应使用地图。这里最好使用forEach,像这样:

let flagUrls = [];
let countryNames = [];
country.forEach((country, index) => {
   flagUrls.push(country.flagUrls);
   countryNames.push(country.countryNames);
});

为此使用解构,将传递给提供的函数 country 的第一个参数替换为以下值:{flagUrls, countryNames}

country.forEach(({flagUrls, countryNames}, index) => {
   flagUrls.push(flagUrls);
   countryNames.push(countryNames);
});

创建两个数组的正确方法是调用 map 两次:

const flagUrls = countries.map(country => country.flagUrl);
const countryNames = countries.map(country => country.countryName);

如果你只想用一次迭代来完成它,那么你将不得不使用一个有副作用的循环——类似于你所做的 map 调用,但你更愿意使用 forEach:

let flagUrls = [];
let countryNames = [];
countries.forEach((country, index) => {
    flagUrls[index] = country.flagUrl;
    countryNames[index] = country.countryName;
});

或者只是

let flagUrls = [];
let countryNames = [];
for (const country of countries) {
    flagUrls.push(country.flagUrl);
    countryNames.push(country.countryName);
}