在 JavaScript 中交换数组元素
交换两个元素的传统方法是使用临时变量。 在 JavaScript 中,我们可以轻松地将数组对象重新分配给默认设置为数组对象的变量,并使过程更进一步,以交换两个数组的元素。
同样,ES6 约定为普通变量和对象带来了更高效的交换。 另一种方法是使用另一种传统方法,即使用循环遍历数组元素并交换它们,读取索引。
这种方式太费时,还要考虑一些额外的代码行。
在这里,我们将看到所有可使交换任务更加灵活的优选示例。 让我们进入代码库!
在 JavaScript 中使用临时变量交换数组元素
在下面的示例中,我们将采用两个具有相应元素的数组。 我们的目标是分配一个新变量并将其中一个数组传输到那里。
然后将另一个数组重新分配给刚刚将其内容转移到变量的数组。 最后,将变量内容转移到我们选择的最后一个数组。
这是数组元素临时变量切换的基本操作。
代码片段:
var x = [1,2,3];
var y = [4,5,6];
var a;
a=x;
x=y
y=a;
console.log(x)
console.log(y)
输出:
如您所见,x 包含 [1,2,3],y 包含 [4,5,6]。 当交换开始时,变量 a 获取 x 的元素,而 x 接收 y 的元素。
对于最后一步,y 附加 a 的内容。 结果推断出交换结果。
使用 ES6 析构函数赋值在 JavaScript 中交换数组元素
ES6 的析构函数赋值可以更轻松地交换两个数组,并且只需要一行代码。 只需要对方括号中的数组进行赋值,将右边倒置即可。
如果仔细观察,设置析构函数分配的模式是毫不费力的。
代码片段:
var x = [1,3,5];
var y = [2,4,6];
[x,y]=[y,x]
console.log(x)
console.log(y)
输出:
使用按位异或和数组迭代在 JavaScript 中交换数组元素
除了上面提到的两种约定,还有多种交换数组元素的方法。 您可以使用减法、按位 XOR 运算或通过对数组应用迭代来使用临时变量规则进行交换。
在这里,我们计算了 XOR 操作来交换两个数组的元素。
代码片段:
var x = [7,42,7];
var y = [4,5,6];
if(x.length == y.length){
for(var i=0;i<x.length;i++){
x[i] = x[i] ^ y[i]
y[i] = x[i] ^ y[i]
x[i] = x[i] ^ y[i]
}
}
console.log(x)
console.log(y)
输出:
让我们考虑这个例子,x[0] = 7 和 y[0] = 4。当我们执行 7^4 时,7 对应的位模式是 111,4 是 100。
在第一个 XOR 之后,我们得到 011,存储为 x[0]。 对于下一个 XOR,我们有 x[0] = 3 (011)
和 y[0] = 100,所以在这种情况下,结果存储在 y[0] 中是 111 = 7。
在 x[0] 中,我们将得到 111^011 = 100 (4)
。 因此,我们交换了 x 和 y 数组的第一个元素,我们可以为每个索引元素重复此迭代。
相关文章
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 事件。