简体   繁体   中英

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 -- is this acceptable? 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.

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. 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.

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]);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM