javascript - How to invert boolean arrays inside another array with map and forEach?
问题描述
I'm trying to reverse and invert arrays inside a two-dimensional array.
let a = [[true, false, false], [false, true, true]];
I've made a function that takes in two-dimensional array a
and does a forEach
on it. This takes each inner array and reverses it. I then try to take the indivual array that was just reversed and try to do map
on it to invert each value inside the array (bool => !bool
).
This function seems to work up to the reverse()
, but I can't figure out why the map()
doesn't seem to work. Is it impossible to chain looping / iterative arrow functions like this?
var reverseInvert = a => {
a.forEach(arr => arr.reverse().map(bool => !bool));
return a;
};
expected result:
[[ true, true, false], [false, false, true]]
actual result:
[[false, false, true], [true, true, false]]
解决方案
.map
always creates a new array - the existing array will not be mutated. Either .map
to create a new larger array:
let a = [[true, false, false], [false, true, true]];
var reverseInvert = a => {
const newA = a.map(arr => arr.reverse().map(bool => !bool));
return newA;
};
console.log(reverseInvert(a));
Or, if you want to mutate (not recommended unless necessary), you'll have to explicitly reassign the new mapped inner array to the index on the outer array:
let a = [[true, false, false], [false, true, true]];
var reverseInvert = a => {
a.forEach((arr, i, outerArr) => {
outerArr[i] = arr.reverse().map(bool => !bool)
});
return a;
};
console.log(reverseInvert(a));
推荐阅读
- java - 并发作业执行在春季批处理中不起作用
- html - 如何使标题栏上的图像四舍五入?
- c++ - 在 DirectX 12 中创建纹理的问题
- bash - 提取具有非特定分隔符的大型数据集的块
- scala - 如何识别在 Spark 中出现错误的列?
- umbraco - Umbraco 检查 - 如何处理搜索词中的引号?
- c# - 当我发出 http put 请求时,内容始终为空
- python - Python WSGI Repoze.who 基本身份验证不要求用户和密码
- android-studio - 我无法使用 Firefox 开发者版从网上下载 Android Studio
- tomcat8 - 希望将 Java 项目从 tomcat 9 迁移到 tomcat 8.5(降级)