[英]Nested (Condition) ? true:false statements in JavaScript
In the following code snippet, 在以下代码段中,
var paintMode = data.hasOwnProperty('regions') ?
'regions' : data.hasOwnProperty('vpcs') ?
'vpcs' : data.hasOwnProperty('zones') ?
'zones' : data.hasOwnProperty('subnets') ?
'subnets' : data.hasOwnProperty('clusters') ? 'clusters' : null;
I've used a deeply nested (condition) ? true : false
我使用了一个嵌套的
(condition) ? true : false
(condition) ? true : false
-- is this acceptable? (condition) ? true : false
这可以接受吗? is it optimized? 优化了吗? If its bad is there an alternative?
如果不好,还有其他选择吗?
It is used inside a recursive function which does a few SVG operations, here's the function snippet if you are curious. 它在执行一些SVG操作的递归函数中使用,如果您好奇的话,这里是函数片段。
function paintGroups(data) {
var paintMode = data.hasOwnProperty('regions') ? 'regions' : data.hasOwnProperty('vpcs') ? 'vpcs' : data.hasOwnProperty('zones') ? 'zones' : data.hasOwnProperty('subnets') ? 'subnets' : data.hasOwnProperty('clusters') ? 'clusters' : null,
depth = data[paintMode].length,
i,
Shape; //= raphealObj.rect();
// Register stacking order
// Paint a shape with styles based on paintMode
// Store its id & Label for other ops.
if(paintMode) {
for(i = 0; i < depth; i++) {
paintGroups(data[paintMode][i]);
}
}
// to reverse the order of paint - place your statements here
}
Generally speaking using binary operations should be faster than conditional statements with branching because of branch prediction, caching, yada yada yada. 一般来说,由于分支预测,缓存,yada yada yada,使用二进制操作应该比带有分支的条件语句更快。 But your code is fine.
但是您的代码很好。 I like the && ||
我喜欢&& || but it's just a preference and not based on anything empirical.
但这只是一个偏好,并不基于任何经验。
var data = {a: 1, b: 2, c: 3};
var result = data.x ||
data.y && "y" ||
data.z && "z" ||
data.w && "w" ||
null;
I didn't feel like typing .hasOwnProperty. 我不想键入.hasOwnProperty。
EDIT After actually looking at your code 编辑实际查看您的代码后
var paintMode = data.regions || data.vpcs || data.zones || data.subnets || data.clusters || null;
if(paintNode) {
for(var i=0; i<paintMode.length; i++)
paintGroups(paintMode[i]);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.