简体   繁体   中英

Best way to align/indent code for a multiline JS object?

Is there a 'best way' or 'standard way' to align JS objects?

Here are some different examples:

Align keys

        var boundBox = {x: click.x - boundBoxDefaultSize/2,
                        y: click.y - boundBoxDefaultSize/2,
                        width: boundBoxDefaultSize,
                        height: boundBoxDefaultSize }

Align colons

        var boundBox = {x: click.x - boundBoxDefaultSize/2,
                        y: click.y - boundBoxDefaultSize/2,
                    width: boundBoxDefaultSize,
                   height: boundBoxDefaultSize }

One line

        var boundBox = {x: click.x - boundBoxDefaultSize/2, y: click.y - boundBoxDefaultSize/2, width: boundBoxDefaultSize, height: boundBoxDefaultSize }

The majority of code out there aligns objects like this:

var boundBox = {
      x: click.x - boundBoxDefaultSize/2,
      y: click.y - boundBoxDefaultSize/2,
      width: boundBoxDefaultSize,
      height: boundBoxDefaultSize 
}

If it's short enough, it can be all on one line:

 var boundBox = {x:x, y:y}

I hope that helps you.

I highly recommend you this Style guide https://github.com/airbnb/javascript

So, your code should be as follows:

var boundBox = {
  x: click.x - boundBoxDefaultSize/2,
  y: click.y - boundBoxDefaultSize/2,
  width: boundBoxDefaultSize,
  height: boundBoxDefaultSize
};

One line (when enough) is fine, and so is lining up keys. I've never seen lining up on colons. If you want more structure, better line up both keys and values:

        var boundBox = {x:      click.x - boundBoxDefaultSize/2,
                        y:      click.y - boundBoxDefaultSize/2,
                        width:  boundBoxDefaultSize,
                        height: boundBoxDefaultSize };

Notice that it is also customary to use linebreaks around the braces of multiline literals, to make it look less like LISP and more like a block:

        var boundBox = {
            x:      click.x - boundBoxDefaultSize/2,
            y:      click.y - boundBoxDefaultSize/2,
            width:  boundBoxDefaultSize,
            height: boundBoxDefaultSize
        };

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