如何使用许多if / else循环来压缩此代码 [英] How do I supress this code rather using many if/else loops

查看:73
本文介绍了如何使用许多if / else循环来压缩此代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们正在提交一份注册表,用户必须在其中输入我们提供某些警报的详细信息。现在的问题是,我们可以通过代码来检查验证,而不是使用许多ifelse循环。(我认为我们可以使用for循环)如果有人放下代码会很高兴



we are submitting a registration form, where in the user has to input the details for that we are providing certain alerts.Now the question is instead of using many ifelse loops can we supress the code for checking the validations.(i think we can do using for loop) Would be happy if any anyone puts the code

function validateFields() {

	valid = true;
	if (isEmpty(frm.id)) {
		alert("ID cannot be empty");
		valid = false;

	} else if (isEmpty(frm.name)) {
		alert("Name cannot be empty");
		valid = false;

	}

	else if (isEmpty(frm.age)) {
		alert("Age cannot be empty");
		valid = false;
	}
	else if (isEmpty(frm.mobile)) {
		alert("Mobile cannot be empty");
		valid = false;
	}
	else if (isEmpty(frm.email)) {
		alert("Email cannot be empty");
		valid = false;
	
	} 
	else if (isEmpty(frm.city)) {
		alert("city cannot be empty");
		valid = false;
	}

	else if (isNaN(frm.age.value)) {
		alert("Age should be a number");
		valid = false;
	}

	

	else if (isNaN(frm.mobile.value)) {
		alert("Mobile should be a number");
		valid = false;
	}

	
	return valid;

}

function isEmpty(obj) {
	if (obj.value == "")
		return true;
	else
		return false;
}

推荐答案

有一种方法有点黑客攻击。您可以使用开关(true)



There is a way that is a bit of a hack. You can use switch(true):

var a = true;
var b = false;

switch(true){
    case a && b:
        alert("a && b");
        break;
    case b:
        alert("b");
        break;
    case b && !a:
        alert("b && !a");
        break;
    case a || b:
        alert("a || b");
        break;
    case a:
        alert("a");
        break;
    case a && !b:
        alert("a && !b");
        break;
    default:
        alert("default");
        break;
}





当a = false且b = false时,警报为默认。

当a = false且b = true时,警报为b。

当a = true且b = false时,警报为a || b。

当a = true且b = true时,警报为a&& b。



break; 就像 else 一样。你可以省略 break; 所以它就像一个的列表,如果而不是 else如果 s



希望有所帮助^ _ ^

Andy



PS:你可以在这里玩这个例子:

在jsfiffle.net上切换(true) [ ^ ]



when a=false and b=false, the alert is "default".
when a=false and b=true, the alert is "b".
when a=true and b=false, the alert is "a || b".
When a=true and b=true, the alert is "a && b".

The break; is like the else here. You can omit the break; so it acts like a list of ifs instead of else ifs

Hope that helps ^_^
Andy

PS: you can play with this example here:
switch(true) on jsfiffle.net[^]


这篇关于如何使用许多if / else循环来压缩此代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆