javascript - 在 Javascript 中交换两个数组之间的两个元素

标签 javascript arrays

假设我有两个不同的数组:

const a = ['a', 'b', 'c', 'd', 'e', 'f'];

const b = ['g', 'h', 'i', 'j', 'k', 'l'];

我想将“c”放在“l”的位置上,反之亦然,如下所示:

const a = ['a', 'b', 'l', 'd', 'e', 'f'];
const b = ['g', 'h', 'i', 'j', 'k', 'c'];

我怎样才能实现这个目标?

我这样做是因为我在页面中组织一组值,并且每个页面最多包含 6 个元素

最佳答案

您可以使用数组解构来交换元素。

const a = ['a', 'b', 'c', 'd', 'e', 'f'];
const b = ['g', 'h', 'i', 'j', 'k', 'l'];
let idxC = a.indexOf('c'), idxL = b.indexOf('l');
[a[idxC], b[idxL]] = [b[idxL], a[idxC]];
console.log(JSON.stringify(a));
console.log(JSON.stringify(b));

关于javascript - 在 Javascript 中交换两个数组之间的两个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71505334/

相关文章:

javascript - 为什么 for 循环不从数组中删除每个奇数(使用 splice 方法)?

Javascript 适用于除 IE 9 以外的所有浏览器

javascript - 在 Javascript 中将 Json 数组转换为数组

javascript - Ace Editor - 如何找到一个或所有实例?

arrays - O(nlogS) 中 +ve 个整数的连续子数组的第 K 个最大和

php - 具有多态关系的多维数组(树结构)

javascript - 如何获取:contains() Selector using an Array with multiple matches in a DIV?的总实例

c - 简单的C程序错误

javascript - 如何在 mysql 中将多个结果连接成几个通用结果?

javascript - 在页面加载时调整 Canvas 大小