9宫格键盘数字对应字母组合实现

  • Post author:
  • Post category:其他


const rules = {
  2: ['a', 'b', 'c'],
  3: ['d', 'e', 'f'],
  4: ['g', 'h', 'i'],
  5: ['j', 'k', 'l'],
  6: ['m', 'n', 'o'],
  7: ['p', 'q', 'r', 's'],
  8: ['t', 'u', 'v'],
  9: ['w', 'x', 'y', 'z']
}

const getData = (arr, result, index) => {
  const newArr = [];
  arr.forEach((it, idx) => {
    if (index === 0) {
      result.push([it]);
    } else {
      result.forEach((r, rIdx) => {
        if (r.length <= index) {
          r.push(it);
        } else {
          newArr.push(r.slice(0, r.length - 1).concat(it));
        }
      })
    }
  });
  return result.concat(newArr);
};

const getStr = (str) => {
  const s = typeof str === 'number' ? str.toString() : str;
  const arr = s.split('');
  const resultArr = [];
  arr.forEach(it => resultArr.push(rules[it]));
  let result = [];
  resultArr.forEach((it, index) => {
    result = getData(it, result, index);
  });
  return result.map(it => it.join(''));
}

const _result = getStr(234);
console.log(_result.length, JSON.stringify(_result));



版权声明:本文为weixin_43664308原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。