【发布时间】:2022-01-19 15:22:49
【问题描述】:
我将优化 javascript 代码,我看到旧代码如下所示,
var emcont = $('#emcont').val();
numericMatch = emcont.match(/\d/g);
if (numericMatch == null) {
isValid = false;
$('#msg_emcont').html(getMessage('msg_emcont')).show();
} else if (emcont.length != 14) {
isValid = false;
$('#msg_emcont').html(getMessage('msg_emcont')).show();
} else if (numericMatch.length && numericMatch.length != 10) {
isValid = false;
$('#msg_emcont').html(getMessage('msg_emcont')).show();
} else {
$('#msg_emcont').html('').hide();
}
我打算将 if-else 条件转换为 switch 条件,但上面代码中的问题是第二个条件验证使用了emcont 变量,所以我不能在switch 语句中直接使用numericMatch。所以我决定直接在switch 语句中使用emcont 变量,如下面的代码,
switch(emcont)
{
case emcont.match(/\d/g) == null:
isValid = false;
$('#msg_emcont').html(getMessage('msg_emcont')).show();
break;
case emcont.length != 14:
isValid = false;
$('#msg_emcont').html(getMessage('msg_emcont')).show();
break;
case emcont.match(/\d/g).length && emcont.match(/\d/g).length != 10:
isValid = false;
$('#msg_emcont').html(getMessage('msg_emcont')).show();
break;
default:
$('#msg_emcont').html('').hide();
break;
}
在 switch case 验证中使用的正则表达式,所以我需要知道哪个代码在性能方面更好。
【问题讨论】:
-
你不能这样使用 switch 语句。 developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
-
和...Which is faster
-
为什么人们认为代码迁移到交换机会更好?想让你的代码更好吗?停止一遍又一遍地在 DOM 中查找元素。
-
你的开关应该是
switch(true),但这样使用它只是不好的做法。 -
你可以只用一个正则表达式来测试它。真的不需要3次检查。你期望的模式是什么?像 XXX-1234567890 之类的东西???
标签: javascript performance optimization complexity-theory