分享

web前端js中ES6的规范写法

 昵称65038308 2020-07-16

1、引号的使用,单引号' ' 优先(如果不是引号嵌套,不要使用双引号) 

正常情况:console.log('hello there') ,双引号转码: $("<div class='box'>")

2、空格的使用问题:(关键字后  符号后 排版 函数 赋值符号= )等

a 函数的括号:function hello  (name)  {}    看 (参数)的 "括号外左右"(  ) 是有空格的,"括号内name左右" 是没有空格的

b 关键字后需要空格:if  (condition) { ... }  if和()之间需要有空格

c 赋值符号 = 两边需要有空格 :var x  =  2  赋值符号 = 两边需要空格

d 字符串拼接符号 + 两边需要空格:var message = 'hello, '  +  name  +  '!' 常量和变量之间的+号,左右两边需要空格

e 逗号,前面不要留空格,后面留空格:var list = [1,  2,  3,  4]          function greet  (name,  options)  { ... } 逗号前面不留后面留空格

3、同行不同行的问题:

if () {}else{}中:  } else { 要在一行内
if (true) {
  // 
}  else   {
  //
}

4、不写没有使用过的变量,如果定义了一个变量,后来一直没有参与过运算,那么不应该定义这个变量。

5、用=== 代替 ==,比较相等的时候,因为 == 会多一步数据转换,但是当在 if (a!=undefiend) {}条件中, a!=undefiend同时有a!==undefiend和a!==null的双重意思(null == undefined)

 

6、习惯给window的属性和方法加上window,例外的几个不用加window:document ,console ,navigator。  如:window.alert('hi')

7、同一个连写方法很长要换行缩进问题,js中三元运算符,jq中的连缀等

var location = env.development ? 'localhost' : 'www.api.com'  一行内写法

连缀写法:

var leds = stage.selectAll('.led')
    .data(data)
  .enter().append('svg:svg')
    .class('led', true)
    .attr('width', (radius + margin) * 2)
  .append('svg:g')
    .attr('transform', 'translate(' + (radius + margin) + ',' + (radius + margin) + ')')
    .call(tron.led);

 8、注释问题:要有与前一行要空一行,另外不要无缘无故有大片的空白行// 后面空一格

var value  =  'hello world';空一行

//这里是注释   
console.log(value)

多行注释:(这也可以用到版权信息注释

/**
* make() returns a new element
* based on the passed in tag name
*
* @param <String> tag
* @return <Element> element
*/

9、开头问题:不要  (   [   `   开头, 在开头前要加上;号

;(function () {window.alert('ok')}())
;[1, 2, 3].forEach(bar)    
;`hello`.indexOf('o')

10、对象和数组的创建问题:var item = {}; 不用new Object()方式             数组:var arr = []

11、超过80个字的字符串连接问题:

var errorMessage = 'This is a super long error that ' +
   'was thrown because of Batman.'+
     'When you stop to think about ' +
    'how Batman had anything to do '+
     'with this, you would get nowhere ' +
   'fast.';

循环 或者 多行字符串 用join方法来构建

function inbox(messages) {
  items = []; 
  for(i = 0; i < length; i++) {
       items[i] = messages[i].message;
  } 
  return'<ul><li>'+ items.join() + ;
}

12、对数字使用 parseInt 并且总是带上类型转换的基数.     var val = parseInt(inputValue, 10);

13,布尔值转换 用Boolean() 或者 !!        var  hasAge = Boolean(age);     var hasAge = !!age;

14、命名问题:

a 命名私有属性时前面加个下划线 _      如:构造函数中 this._firstName = 'Panda';     var _firstName = firstName; 

b jq变量命名加上个$,用来区分js变量

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多