比较两个数组中是否有相同的元素

双重遍历循环

太过复杂

点击查看代码
let arr1 = [1, 2, 3];
let arr2 = [1, 2, 3, 4];

let hasCommonElement = false;
for (let i = 0; i < arr1.length; i++) {
  for (let j = 0; j < arr2.length; j++) {
    if (arr1[i] === arr2[j]) {
      hasCommonElement = true;
      break; // 找到相同元素后,退出内层循环
    }
  }
  if (hasCommonElement) {
    break; // 找到相同元素后,退出外层循环
  }
}

console.log(hasCommonElement) // 输出结果

集合-Set

let arr1 = [1, 2, 3]
let arr2 = [1, 2, 3, 4]

let set1 = new Set(arr1)
let hasCommonElement = arr2.some(element => set1.has(element))

console.log(hasCommonElement) // 输出结果

ES6提供了新的数据解构Set

  • 类似于数组,但成员的值都是唯一的
  • 集合实现了 iterator 接口,所以可以使用『扩展运算符』和『for...of』进行遍历。
  1. 定义一个Set集合:
let st1=new Set()
let st2=new Set([可迭代对象])

2.集合的属性和方法

st.size:返回集合个数
st.add(item):往集合中添加一个新元素 item,返回当前集合
st.delete(item):删除集合中的元素,返回 boolean 值
st.has(item):检测集合中是否包含某个元素,返回 boolean 值
st.clear():清空集合
集合转为数组:[...st]
合并两个集合:[...st1, ...st2]

数组的includes()和some()

let arr1 = [1, 2, 3]
let arr2 = [1, 2, 3, 4]

let hasCommonElement = arr1.some(element => arr2.includes(element))

console.log(hasCommonElement) // 输出结果
posted @ 2024-07-09 09:33  齐嘉树  阅读(8)  评论(0编辑  收藏  举报