第一种
let arr1 = [1,2,3,4,5,6];
let arr2 = [4,5,6,8,9,10];
let result = new Array();
let c = arr2.toString();
//获取两个数组的相同元素
for (var i = 0; i < arr1.length; i++) {
if (c.indexOf(arr1[i].toString()) > -1) {
for (var j = 0; j < arr2.length; j++) {
if (arr1[i] == arr2[j]) {
result.push(arr1[i]);
break;
}
}
}
}
console.log(result)
第二种
var arr1 = [0,1,2,3,4,5];
var arr2 = [0,4,6,1,3,9];
function getArrEqual(arr1, arr2) {
let newArr = [];
for (let i = 0; i < arr2.length; i++) {
for (let j = 0; j < arr1.length; j++) {
if(arr1[j] === arr2[i]){
newArr.push(arr1[j]);
}
}
}
return newArr;
}
console.log(getArrEqual(arr1, arr2));
//输出:(4) [0, 4, 1, 3]
网友评论