时间:2021-08-22 09:48:26 | 栏目:JavaScript代码 | 点击:次
1、取出两个数组的不同元素
var arr1 = [0,1,2,3,4,5]; var arr2 = [0,4,6,1,3,9]; function getArrDifference(arr1, arr2) { return arr1.concat(arr2).filter(function(v, i, arr) { return arr.indexOf(v) === arr.lastIndexOf(v); }); } console.log(getArrDifference(arr1,arr2)); //输出:(4) [2, 5, 6, 9]
(1)concat() 方法:用于连接两个或多个数组。
该方法不会改变现有的数组,而仅仅会返回被连接数组的一个副本,例:
<script type="text/javascript"> var arr = new Array(3) arr[0] = "George" arr[1] = "John" arr[2] = "Thomas" var arr2 = new Array(3) arr2[0] = "James" arr2[1] = "Adrew" arr2[2] = "Martin" document.write(arr.concat(arr2)); //输出:George、John、Thomas、James、Adrew、Martin </script>
(2)Array filter() 方法:
(3)indexOf() 方法:
(4)lastIndexOf() 方法:
2、取出两个数组的相同元素
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]