如何映射数组并返回它



我有一个数组数组,我想映射到它上面并返回数组的值,但当我映射到它上并记录结果时,它只是一个数组,我不知道如何映射到我的数组上并在其他地方使用它。

const arr = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
];
const arrMap = arr.map((it) => it.map((itm) => itm));
console.log(arrMap);

//what I expected 1,2,3,4,5,6 , ...
//what I got [Array(3), Array(3), Array(3)]

事实上,我需要在其他地方使用它们的值,但我不知道该怎么办。我也使用了函数,但当我返回值并记录它们时,它是未定义的:

const arr = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
];

const arrMap = (arr) => {
arr.forEach((element) => {
console.log(element);
//In here, everything works fine
return element;
});
};
console.log(arrMap);
//what I got undefined

使用flatMap-

const arr = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
];
const arrMap = arr.flatMap(m => m);
console.log(arrMap);

为什么它不起作用:map()应该在数组的每个元素上运行,并返回相同长度的转换数组。您的输入数组中有三个元素,并且在映射的数组中总是会得到三个元素。

如果您愿意,可以通过使用forEach()调整代码来满足您的期望。对于forEach(),不会返回任何内容,您将不得不从一个单独的数组变量开始。以下代码使用...

const arr = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
];
let arrMap = [];
arr.forEach((it) => arrMap.push(...it));
console.log(arrMap);

flatMap()已经存在:

const arr = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
];

let ans = arr.flatMap(x => x);
console.log(ans);

如果只想压平数组,请使用flat:

const arr = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
];
console.log(arr.flat());

如果要在阵列变平之前对每个元素执行某些操作,请使用flatMap。

const arr = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
];
const arrMap = arr.flatMap((el) => {
el.forEach((n) => console.log(n));
return el;
});
console.log(arrMap);

forEach不返回任何类似于for循环的内容,但仅返回for数组。既然你有双阵列,你应该使用flatMap 来平坦它

const arr = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
];
const arrMap = arr.flatMap((it) => it);
console.log(arrMap);

最新更新