描述:
难点:
将[[‘a’,‘b’,‘c’],[‘d’,‘e’,‘f’]]输出为[“ad”, “ae”, “af”, “bd”, “be”, “bf”, “cd”, “ce”, “cf”].
关键代码描述:
1.假设我们已经根据输入的数字得到了 rawArr = [[‘a’,‘b’,‘c’],[‘d’,‘e’,‘f’]]
2. 下一步将rawArr[0]中的每一个元素与 rawArr[1]中的每一个元素相加…
3. reduce是对数组中相邻的元素进行操作,并将结果保留…
// 实现.
rawArr.reduce( (a,b) =>{let tmpArr= [];a.forEach(ai=>{b.forEach(bi =>{tmpArr.push(ai + bi);}}
}
总体代码:
var letterCombinations = function(digits) {if(digits.length < 1) return []let map = new Map();map.set('2',['a','b','c']);map.set('3',['d','e','f']);map.set('4',['g','h','i']);map.set('5',['j','k','l']);map.set('6',['m','n','o']);map.set('7',['p','q','r','s']);map.set('8',['t','u','v']);map.set('9',['w','x','y','z']);digits = digits.replace(/1/g,'');let rawArr = [];digits.split('').forEach(item=>{rawArr.push(map.get(item))})let retArr = rawArr.reduce((a,b)=>{let tmpArr = [];a.forEach((ai)=>{b.forEach((bi)=>{tmpArr.push(ai + bi)})})return tmpArr})return retArr
};