js 使用forEach代替if判断

js yekong 1013℃

登录页面有个要求,根据接口返回的数据依次判断类型,1-4,有1就先跳转到1,依次进行判断,一开始用的是if的判断形式,在做代码精简时,又想到了用循环的方式forEach。类型少的时候用if和forEach都可以,当类型多的时候,forEach代码要更精简一些。

if

if (this.listtype.indexOf(1) != -1) {
					uni.setStorageSync('uid', that.list[this.listtype.indexOf(1)].Id)
					uni.setStorageSync('userData', JSON.stringify(that.list[this.listtype.indexOf(1)]))
					uni.redirectTo({
						url: '/pages/home/enterprise/index'
					})
				} else if (this.listtype.indexOf(2) != -1) {
					uni.setStorageSync('uid', that.list[this.listtype.indexOf(2)].Id)
					uni.setStorageSync('userData', JSON.stringify(that.list[this.listtype.indexOf(2)]))
					uni.redirectTo({
						url: '/pages/home/client/index'
					})
				} else if (this.listtype.indexOf(3) != -1) {
					uni.setStorageSync('uid', that.list[this.listtype.indexOf(3)].Id)
					uni.setStorageSync('userData', JSON.stringify(that.list[this.listtype.indexOf(3)]))
					uni.redirectTo({
						url: '/pages/home/owner/index'
					})
				} else if (this.listtype.indexOf(4) != -1) {
					uni.setStorageSync('uid', that.list[this.listtype.indexOf(4)].Id)
					uni.setStorageSync('userData', JSON.stringify(that.list[this.listtype.indexOf(4)]))
					uni.redirectTo({
						url: '/pages/home/driver/index'
					})
				} else {
					uni.redirectTo({
						url: '/pages/home/home'
					})
				}

forEach

var list = [1, 2, 3, 4]
						list.forEach(function(item, index) {
							if (that.listtype.indexOf(item) != -1) {
								that.changeStorage(item)
								num = item
								uni.redirectTo({
									url: that.pageList[item]
								})
								throw new Error("中断循环");
							}
						});
						if (num == 0) {
							uni.redirectTo({
								url: that.listtype[0]
							})
						}
喜欢 (0)