鍍金池/ 問答/Python  HTML/ js中有沒有快速生產(chǎn)list array的方式?

js中有沒有快速生產(chǎn)list array的方式?

現(xiàn)有a、b,

a = [1,2];
b = ['a','b'];

如何快速生成
[[1,'a'], [1,'b'],[2,'a'],[2, 'b']]

兩次for循環(huán) 感覺有點不太方便。 有沒有簡便的快速寫法?

有個類似的問題 ---> 這里。

回答
編輯回答
舊酒館
2017年9月18日 03:40
編輯回答
孤毒

想到了一個場景 關(guān)鍵詞組合
在數(shù)組是可變量延伸成多維并順序可顛倒、同求個思路、感謝

2017年1月26日 01:45
編輯回答
神曲

沒有現(xiàn)成的使用lodash的函數(shù)庫你可以輕松實現(xiàn)功能
import { flatMap, map } from 'lodash';

flatMap([1, 2], i => map(['a', 'b'], j => [i, j]))

可以自己寫一個通用函數(shù)

const nest = (xs, ys, predicate) => flatMap(xs, x => map(ys, y => predicate(x, y)))

這樣使用nest([1, 2], ['a', 'b'], (x, y) => [x, j])

2018年7月8日 19:47
編輯回答
涼薄

用數(shù)組推倒是最簡潔的,

var a3 = [for(i of a) for(j of b)[i, j]]

請用 firefox 看:
https://jsfiddle.net/ex0os1Lh/1/

數(shù)組推倒: https://developer.mozilla.org...

2018年2月26日 21:18
編輯回答
巷尾
a = [1,2];
b = ['a','b'];
c = [];
a.forEach(aitem => b.forEach(bitem => c.push([aitem,bitem])));

這樣可以嗎

2018年6月1日 18:41