在 JavaScript 中转置数组
与许多其他编程语言一样,JavaScript 中的对象可以与现实生活中的对象进行比较。
在 JavaScript 中,对象是具有属性和类型的独立实体。例如,自行车是具有颜色、设计、型号、品牌等的对象。
数组是特殊类型的对象,其键是数字预定义的。任何 JavaScript 对象都可以转换为数组。
数组必须使用整数而不是字符串作为元素索引。本文介绍了如何在 JavaScript 中转置数组。
转置矩阵是通过线性代数将矩阵转换为矩阵概念的最常用方法之一。通过将给定矩阵的行更改为列以及将列更改为行来获取矩阵的转置。
它在要获得矩阵的逆矩阵和伴随矩阵的应用中特别有用。
二维数组是具有共同名称的元素的集合,并被组织为行和列的数组。二维数组是数组的数组,所以让我们创建一个一维数组对象的数组。
由于为调用数组的每个元素调用提供的函数,map()
方法会创建一个新数组。该映射按顺序为数组的每个元素调用一次提供的 callbackFn
函数,并根据结果创建一个新数组。
callbackFn
仅对具有赋值的数组索引(包括未定义的索引)调用;由于缺少数组元素,即从未配置过的索引和已删除的索引,它不会被调用。
语法:
// Arrow function
map((element, index) => { /* Perform operation */ })
// Callback function
map(callbackFn, thisArg)
// Inline callback function
map(function(element, index, array) { /* Perform operation */ }, thisArg)
callbackFn
是为每个数组元素调用的函数。每次执行 callbackFn
时,都会将返回值添加到 newArray
。
callbackFn
函数接受三个参数。
thisArg
是一个可选参数,表示执行 callbackFn
时的值。此参数返回一个新数组,其中数组的每个元素都是回调函数的输出。
你可以在 map()
的文档中找到有关地图的更多信息。
我们以 OS Array 为例;我们将创建一个 OS 的二维数组并将它们转置到新数组中。
例子:
const osArray = [
['Linux','Windows','MacOS'],
['Linux','Windows','MacOS'],
['Linux','Windows','MacOS'],
];
const transposedOSArray = osArray[0].map((_, colIndex) => osArray.map(row => row[colIndex]));
console.log(transposedOSArray);
我们定义了一个二维数组;我们使用带有元素和列索引的 map
函数。使用嵌套的 map
函数再次迭代每个元素,并在行内返回该特定索引的元素。
在任何浏览器中运行上面的代码都会打印出类似这样的内容。
输出:
[['Linux', 'Linux', 'Linux'], ['Windows', 'Windows', 'Windows'], ['MacOS', 'MacOS', 'MacOS']]
相关文章
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 选择器的不同方法。你还将找到许多有用的
jQuery 中的 Window.onload 与 $(document).ready
发布时间:2024/03/24 浏览次数:180 分类:JavaScript
-
本教程演示了如何在 jQuery 中使用 Window.onload 和 $(document).ready 事件。