javascript:除去数组的重复项

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>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值