[英]javascript hash values validation
I'm trying to give the same behaviour to 4 values in my hash array. 我试图给我的哈希数组中的4个值相同的行为。
For example: 例如:
var array = {};
if (array[key].config.tmp == undefined) {
array[key].config.tmp = {}
}
if(array[key].config.tmp.tp1){
}
if(array[key].config.tmp.tp2){
}
if(array[key].config.tmp.tp3){
}
if(array[key].config.tmp.tp4){
}
Since tp1, tp2, tp3 and tp4 will have the same behaviour. 由于tp1,tp2,tp3和tp4具有相同的行为。 I would like to simplify the validation.
我想简化验证。
Something like: 就像是:
array[key].config.tmp.[tp1,tp2,tp3,tp4] is possible? array [key] .config.tmp。[tp1,tp2,tp3,tp4]可以吗? Already tried.
已经尝试过。 but it was
但这是
tp1,tp2,tp3 and tp4 may not exist(undefined). tp1,tp2,tp3和tp4可能不存在(未定义)。 (tp1 and tp2 only sometimes).
(有时只有tp1和tp2)。
Any advice so I won't duplicate code? 有什么建议可以避免重复代码吗?
Thanks in advance 提前致谢
use a short-circuit operator like ||
使用
||
类的短路运算符 . 。 for instance, if you are checking for the existence of multiple properties, accessing a property which doesn't exist is falsy.
例如,如果您要检查是否存在多个属性,则访问不存在的属性是错误的。
var c = a[key].config.tmp.a || a[key].config.tmp.b || .... || //default
In this example, c will hold the value of the first of these to evaluate to true. 在此示例中,c将保留其中第一个的值以求值为true。 You could also include a "Default" value at the end if they all return false.
如果它们都返回false,则还可以在最后添加一个“默认”值。 Keep in mind that accessing a property of a property that doesn't exist is a type error however, so you must be sure that at least config.tmp exists.
请记住,访问不存在的属性的属性是类型错误,因此,必须确保至少存在config.tmp。 So you can replace your code with
因此,您可以将代码替换为
if (a[key].config.tmp.a || a[key].config.tmp.b || ....) {
}
You could also use a filter on the array keys: 您还可以在数组键上使用过滤器:
if ( ( array[key].config.tmp || {} ).keys().filter(
function(k) { return /^tp[1234]/.test( k ) }
).length ) )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.