关于javascript:数组相关实现

58次阅读

共计 952 个字符,预计需要花费 3 分钟才能阅读完成。

二维数组的排列组合

给一个数组相似 [[“0″,”1”],[“a”,”b”],[“m”,”n”]], 失去后果 [“0am”,”0an”,”0bm”,”0bn”,”1am”,”1an”,”1bm”,”1bn”]

// 给一个数组相似 [["0","1"],["a","b"],["m","n"]], 失去后果 ["0am","0an","0bm","0bn","1am","1an","1bm","1bn"]

function getArrayByArrays(array) {var result = [""];
  for (var i = 0; i < array.length; i++) {result = getValuesByArray(result, array[i]);
  }
  return result;
}
function getValuesByArray(result, inArr) {var arr = [];
  for (var i = 0; i < result.length; i++) {var v1 = result[i];
    for (var j = 0; j < inArr.length; j++) {var v2 = inArr[j];
      var value = v1 + v2;
      arr.push(value);
    }
  }
  return arr;
}

let array = [["0", "1", "2"],
  ["a", "b"],
  ["m", "n", "k", "p"],
];
console.log(getArrayByArrays(array));
// ["0am", "0an", "0ak", "0ap", "0bm", "0bn", "0bk", "0bp", "1am", "1an", "1ak", "1ap", "1bm", "1bn", "1bk", "1bp", "2am", "2an", "2ak", "2ap", "2bm", "2bn", "2bk", "2bp"]

reduce 实现 map

var arr = [1, 2, 3];
// map,返回数组
var arr1 = arr.map((item) => item * 2);
console.log(arr1) // [2, 4, 6]
// reduce,返回数组
var arr2 = arr.reduce((acc, cur) => {acc.push(cur * 2);
  return acc;
}, []);
console.log(arr2); // [2, 4, 6];

正文完
 0