我从数据库中获取数据,其中我只需要两个数组。使用两个变量,我得到了我需要的结果,但我明白,这段代码没有正确编写。甚至 npm 都写箭头函数应该返回一些东西,所以我添加了“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”一词。您需要返回将插入到新数组中的内容。
因此,使用 map
您可以创建一个新数组,其中包含仅具有 flagUrls
和 countryNames
字段的对象,如下所示:
let result = country.map((country, index) => {
return {
flagUrl: country.flagUrls,
countryName: country.countryNames
}
});
如果你想维护两个flagUrls和countryNames数组,你不应该使用map。最好在这里使用 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);
});
关于javascript - 在 JavaScript 中使用解构的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57878577/