简体   繁体   English

在二维数组上使用Array.map

[英]Use Array.map on an 2-dimensional Array

So I have a 2-dimensional Array and want to use a "randomBool" function on each of the elements of the elements in the array. 因此,我有一个二维数组,并希望对数组中元素的每个元素使用“ randomBool”函数。

The "randomBool" function just returns a random boolean: “ randomBool”函数仅返回一个随机布尔值:

const randomBool = () => Boolean(Math.round(Math.random()));

this would be the 2-dimensional Array, that I would input: 这将是我将输入的二维数组:

var test = [
    ["just","some","random","text"],
    [1412,"test",1278391]
]

There is a working for-loop nested in a for-loop: 在for循环中嵌套了一个工作的for循环:

for (let el of test){
    for(let i in el){
        el[i] = randomBool();
    }
}

I tried this: 我尝试了这个:

test.forEach(el => el.map(el2 => randomBool()));

But it didn't work. 但这没有用。 Why? 为什么?

You need to use two nested maps. 您需要使用两个嵌套地图。

const randomBools = test.map(outer => outer.map(inner => randomBool()))

forEach is usually intended to iterate over each item in order to perform some kind of side effect without returning anything and without mutating the original array. forEach通常旨在遍历每个项目,以执行某种副作用,而不会返回任何内容且不会更改原始数组。 For example, printing each item to the console. 例如,将每个项目打印到控制台。

map , on the other hand, is intended to take an array and return a new array of the same size, with the values transformed in some way, without mutating the original array. 另一方面, map旨在获取一个数组并返回一个相同大小的新数组,并以某种方式转换值,而不会使原始数组发生变化。 For example, uppercase all the words in a list. 例如,将列表中的所有单词都大写。

Since you want to return a new 2 dimensional from your existing 2 dimension array with some data transformed, you need to nest your map functions. 由于您要从现有的2维数组返回一个新的2维,并转换一些数据,因此您需要嵌套地图函数。 This will map first over the rows (outer), then the columns (inner). 这将首先映射到行(外部),然后映射到列(内部)。 The results of the inner maps will be collected into the outer map and you'll be left with a 2 dimensional array with your new values, all without modifying the original array. 内部地图的结果将被收集到外部地图中,您将剩下一个带有新值的二维数组,所有这些都无需修改原始数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM