迹忆客 专注技术分享

当前位置:主页 > 学无止境 > WEB前端 > JavaScript >

JavaScript 中压缩数组

作者:迹忆客 最近更新:2023/03/09 浏览次数:

在 JavaScript 中,有时我们希望压缩两个数组。在本篇文章中,我们将研究使用 JavaScript 刷新两个集合。

必须编写 Python zip 函数的 JavaScript 对应项。换句话说,我们需要在给定许多等长集合的情况下创建一个对数组。

在 JavaScript 中,我们可以通过多种方式压缩两个数组,例如使用 map() 方法、Array.from() 方法和 Array.prototype.fill() 方法。

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"]]

使用 map 方法时,确保两个数组的长度必须相同;否则,你将得到结果未定义

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);

你可以看到 ab 数组的长度不同。

输出:

[[9, "1"], [8, "2"], [7, "3"], [6, undefined]]
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"]]

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

Do you understand JavaScript closures?

发布时间:2025/02/21 浏览次数:108 分类:JavaScript

The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.

Do you know about the hidden traps in variables in JavaScript?

发布时间:2025/02/21 浏览次数:178 分类:JavaScript

Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av

How much do you know about the Prototype Chain?

发布时间:2025/02/21 浏览次数:150 分类:JavaScript

The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start

用 jQuery 检查复选框是否被选中

发布时间:2024/03/24 浏览次数:102 分类:JavaScript

在本教程中学习 jQuery 检查复选框是否被选中的所有很酷的方法。我们展示了使用直接 DOM 操作、提取 JavaScript 属性的 jQuery 方法以及使用 jQuery 选择器的不同方法。你还将找到许多有用的

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便