假设有以下两个数组:
const arr1 = [1, 5, 8, 9, 10, 11, 17]
const arr2 = [1, 2, 17, 23, 28, 32]
实现方法 1 (使用for循环) :
const result = []
for (let i = 0; i < arr1.length; i++) {
if (arr2.includes(arr1[i])) {
result.push(arr1[i])
}
}
console.log(result) // [1, 17]
实现方法 2 (使用ES6语法) :
const result = arr1.filter(num => arr2.includes(num))
console.log(result) // [1, 17]