js中断forEach循环

js yekong 1257℃

在对数据进行循环处理处理时,需要对遇到不符合要求的数据对循环进行中断处理,这就需要使用到try catch来实现我们的要求了。

使用try catch实现

try {
	var num = 0
	// 用户类型
	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]
		})
	}
} catch (e) {
	console.log(e)
};

uniapp 循环实例

需求:uniapp项目开发是,表单数据处理,在进行for循环的时候,我们需要判断数据是否符合要求,如果不符合要求则中断循环并报错,方法不在往下走。

实例代码

try {
	var interrupt = false
	if (that.data.Category == 'Ship') {
		if (that.data.Details) {
			that.data.Details.forEach((type) => {
				var datax = {
					Id: type.Id,
					NumberPlate: type.NumberPlate,
					PlannedWeight: type.PlannedWeight
				}
				if (type.PlannedWeight == '') {
					throw new Error("请输入单车计划装车重量");
				}
				Details.push(datax)
			});
		}
	} else {
		if (that.data.Details) {
			that.data.Details.forEach((type) => {
				var datax = {
					Id: type.Id,
					NumberPlate: type.NumberPlate,
					PlannedUnloadingWeight: type.PlannedUnloadingWeight,
				}
				if (type.PlannedUnloadingWeight == '') {
					throw new Error("请输入单车计划卸载重量");
				}
				Details.push(datax)
			});
		}
	}
} catch (e) {
	interrupt = true
	uni.showToast({
		title: e.message,
		icon: 'none'
	})
};
if (interrupt) {
	return
}
喜欢 (1)