java版本的除去数组的重复项已经写过了,这个版本的也差不多,主要是两部操作,一部是合并,一个是遍历顺便去查询数组是否有这个参数,思路都是大同小异,直接上代码吧
<script>
var a1 = [1, 2, 3, 4, 5];
var a2 = [1, 2, 3, 4, 6];
var a = [];
a = a1.concat(a2);
var b = [];
console.log(a);
console.log(a.length);
b.push(a[0]);
a.reduce(function(previousValue, currentValue, index, array) {
if(b.indexOf(currentValue) === -1) {
b.push(currentValue);
}
});
console.log(b);
</script>
主要是使用了concat方法合并数组,再reduce方法遍历数组!但是注意,遍历的时候只是length-1,他不会运行第一个,二是直接把第一个当作是第二个的previsousvalue返回,
对于reduce的使用,有四个参数
上回返回的参数,当前参数的值,下标。数组,:
<script>
var a1 = [1, 2, 3, 4, 5];
var a2 = [1, 2, 3, 4, 6];
var a = [];
a = a1.concat(a2);
var b = [];
console.log(a);
console.log(a.length);
b.push(a[0]);
a.reduce(function(previousValue, currentValue, index, array) {
console.log("当前的值是:");
console.log(currentValue);
console.log("下标为:");
console.log(index);
console.log("数组为:")
console.log(array);
console.log("上回返回的是:")
console.log(previousValue);
console.log("----------------yitiaojiesu")
return "上回返回的数";
if(currentValue.concat(b)) {
b.push(currentValue);
return b
} else {
return currentValue;
}
});
console.log(b);
</script>