gpt4 book ai didi

javascript - 如何以编程方式比较两个不同数组中的所有元素

转载 作者:行者123 更新时间:2023-12-01 00:22:23 26 4
gpt4 key购买 nike

我怎样才能做到这一点,以便我的第一个循环遍历第一个数组,然后另一个循环遍历第二个数组并将第一个数组的每个元素与第二个数组的所有元素进行比较。

例如。//第一个循环遍历我的数组1

for (var i = 0; i < array1.length; i++) {

//to store the element in
var test = array1[i]

//second loop looping through my array 2
for (var j = 0; j < array2.length; i++) {
//compares the current element in the array 1 to all the elements in array 2
if (test == array2[j]) {
alert(array2[j])
}
}
}

所以基本上我想要它,以便当第一个循环位于第一个元素示例 array1[0] 中时,下一个循环应该将 array1[0] 与 array2 中存在的所有元素进行比较,并在完成后下一个元素 array1 [1] 应该是接下来要比较的。

但是当我运行这个时,它只会无限地提醒数组 1 的第一个元素

最佳答案

如果您想找到每个数组的共同元素并警告它,这里就是解决方案。

  const arrayOne = [16, 26, 41];
const arrayTwo = [10, 12, 26];

for (const element of arrayOne) {
if (arrayTwo.includes(element)) {
alert(element);
}
}

A Venn Diagram highlighting the Intersection of Two Sets

关于javascript - 如何以编程方式比较两个不同数组中的所有元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59305577/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com