# JavaScript 中压缩数组

## 在 JavaScript 中使用 `map` 方法压缩数组

JavaScript 中的 `map()` 函数压缩了两个一定长度的数组。但是，如果两个数组的长度不匹配，则会导致 `undefined`

``````let a = [9, 8, 7];
let b = ['1', '2', '3'];
let zip = a.map(function(e, i) {
return [e, b[i]];
});
console.log(zip);
``````

`map()` 方法接受的回调函数将调用 `a` 数组的元素以及与 `a` 集合映射的 `b` 数组的元素。学习如何以这种方式拉上拉链也很简单。

``````[[9, "1"], [8, "2"], [7, "3"]]
``````

``````let a = [9, 8, 7, 6];
let b = ['1', '2', '3'];
let zip = a.map(function(e, i) {
return [e, b[i]];
});
console.log(zip);
``````

``````[[9, "1"], [8, "2"], [7, "3"], [6, undefined]]
``````

## 在 JavaScript 中使用 `Array.from` 方法压缩数组

``````let a = [9, 8, 7, 6];
let b = ['90', '80', '70', '60'];
let zip = (a, b) =>
Array.from(Array(Math.max(a.length, b.length)), (_, i) => [a[i], b[i]]);
console.log(zip(a, b));
``````

`Array.from` 方法的实例中将存在两个数组；它们将被发送到箭头函数。匹配长度后，该过程将映射来自两个单独数组的项目。

``````[[9, "90"], [8, "80"], [7, "70"], [6, "60"]]
``````

``````let a = [9, 8, 7];
let b = ['90', '80', '70', '60'];
let zip = (a, b) =>
Array.from(Array(Math.max(a.length, b.length)), (_, i) => [a[i], b[i]]);
console.log(zip(a, b));
``````

``````[[9, "90"], [8, "80"], [7, "70"], [undefined, "60"]]
``````

`Array.prototype.fill()` 方法的工作原理与 `Array.from()` 方法相同。

``````let a = [7, 8, 9];
let b = ['70', '80', '90'];
let zip = (a, b) =>
Array(Math.max(a.length, b.length)).fill().map((_, i) => [a[i], b[i]]);
console.log(zip(a, b));
``````

``````[[7, "70"], [8, "80"], [9, "90"]]
``````

Shiv is a self-driven and passionate Machine learning Learner who is innovative in application design, development, testing, and deployment and provides program requirements into sustainable advanced technical solutions through JavaScript, Python, and other programs for continuous improvement of AI technologies.