简体   繁体   English

为多行 JS 对象对齐/缩进代码的最佳方法?

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

Is there a 'best way' or 'standard way' to align JS objects?是否有对齐 JS 对象的“最佳方法”或“标准方法”?

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我强烈推荐你这个风格指南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:请注意,习惯上在多行文字的大括号周围使用换行符,使其看起来不像 LISP,而更像一个块:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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