【发布时间】:2019-09-21 23:29:15
【问题描述】:
我正试图围绕 map() 方法,在这种情况下使用它来组合(压缩)两个不同长度的数组。我已经检查过之前关于 JavaScript 压缩的问题,但它们主要关注的是等长数组。
我有两个数组:
const countries = ['US', 'FR', 'IT']
const area = [100, 105, 110, 115, 120, 125, 130]
let merge = countries.map(function (c) {
area.map(function (a) {
return c + a
// This returns an array of length 3 (prints country + all areas into one array position)
// However if I create a third array and use push(c + a) here instead then length is 21 (which is what I am trying to achieve).
})
})
我是否返回了错误的值?就像我在评论中写的那样,如果我将 (c+a) 打印或推送到另一个数组中,那么我会得到所有 21 种可能的组合。 map() 的重点是获得一个新数组,所以我不想推入第三个数组。我还听说嵌套的 forEach 循环是不好的做法(如果我要这样做的话)。
【问题讨论】:
标签: javascript arrays dictionary zip