JavaScript 风格指南(2)

来源:互联网 发布:多玩数据库 7.0 编辑:程序博客网 时间:2024/06/09 23:01

--接 JavaScript风格指南(1) --


四、Arrays


· 4.1 使用字面量的方式创建数组

// badconst items = new Array();// goodconst items = [];

· 4.2 不要使用直接赋值的方式为数组添加新成员,而是使用 push() 方法

const someStack = [];// badsomeStack[someStack.length] = 'abracadabra';// goodsomeStack.push('abracadabra');

· 4.3 使用 ... 拷贝数组

// badconst len = items.length;const itemsCopy = [];let i;for (i = 0; i < len; i += 1) {  itemsCopy[i] = items[i];}// goodconst itemsCopy = [...items];

· 4.4 使用 Array.from() 方法将类数组对象转为数组

const foo = document.querySelectorAll('.foo');const nodes = Array.from(foo);

· 4.5 尽量在数组方法的回调函数中使用 return 语句,当然如果函数体中只有一个没有副作用的表达式的话,可以忽略 return

// good[1, 2, 3].map((x) => {  const y = x + 1;  return x * y;});// good[1, 2, 3].map(x => x + 1);// badconst flat = {};[[0, 1], [2, 3], [4, 5]].reduce((memo, item, index) => {  const flatten = memo.concat(item);  flat[index] = flatten;});// goodconst flat = {};[[0, 1], [2, 3], [4, 5]].reduce((memo, item, index) => {  const flatten = memo.concat(item);  flat[index] = flatten;  return flatten;});// badinbox.filter((msg) => {  const { subject, author } = msg;  if (subject === 'Mockingbird') {    return author === 'Harper Lee';  } else {    return false;  }});// goodinbox.filter((msg) => {  const { subject, author } = msg;  if (subject === 'Mockingbird') {    return author === 'Harper Lee';  }  return false;});

· 4.6 如果数组有多行,请在数组的开头括号和结尾括号处进行换行

// badconst arr = [  [0, 1], [2, 3], [4, 5],];const objectInArray = [{  id: 1,}, {  id: 2,}];const numberInArray = [  1, 2,];// goodconst arr = [[0, 1], [2, 3], [4, 5]];const objectInArray = [  {    id: 1,  },  {    id: 2,  },];const numberInArray = [  1,  2,];


五、Destructuring


· 5.1 当需要访问或者用到对象的多个属性值时,请使用对象解构的方式


理由:对象的解构可以把你从创建对象属性的临时引用这种重复工作中解救出来
// badfunction getFullName(user) {  const firstName = user.firstName;  const lastName = user.lastName;  return `${firstName} ${lastName}`;}// goodfunction getFullName(user) {  const { firstName, lastName } = user;  return `${firstName} ${lastName}`;}// bestfunction getFullName({ firstName, lastName }) {  return `${firstName} ${lastName}`;}

· 5.2 使用数组解构

const arr = [1, 2, 3, 4];// badconst first = arr[0];const second = arr[1];// goodconst [first, second] = arr;

· 5.3 当需要返回多个值时,使用对象解构,而不是数组解构


理由:当下次使用这些返回值的时候,对象解构的方式不需要使用者考虑顺序问题

// badfunction processInput(input) {  // then a miracle occurs  return [left, right, top, bottom];}// 使用者得考虑返回值的顺序 const [left, __, top] = processInput(input);// goodfunction processInput(input) {  // then a miracle occurs  return { left, right, top, bottom };}// 使用者想用什么值直接用就好了 const { left, top } = processInput(input);

六、Strings


· 6.1 使用单引号包裹字符串

// badconst name = "Capt. Janeway";// bad - template literals should contain interpolation or newlinesconst name = `Capt. Janeway`;// goodconst name = 'Capt. Janeway';

· 6.2 过长的字符串也不应该用字符串连接跨行书写


理由:被截断的字符串会增大代码搜索的难度
// badconst 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.';// badconst 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.';// goodconst 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.';

· 6.3 当需要程序构建字符串时,请使用模板字符串,而不是字符串连接符


理由:模板字符串有很多良好的特性,比如合适的换行、变量插入等,这些特点都令其具有良好的可读性和简洁性
// badfunction sayHi(name) {  return 'How are you, ' + name + '?';}// badfunction sayHi(name) {  return ['How are you, ', name, '?'].join();}// badfunction sayHi(name) {  return `How are you, ${ name }?`;}// goodfunction sayHi(name) {  return `How are you, ${name}?`;}

· 6.4 不要使用 eval(),它就是一个魔鬼!


· 6.5 非必要情况下,在字符串中别对字符进行转义


理由:反斜杠会影响代码的可读性,所以除非必须要用反斜杠进行转义,否则别用
// badconst foo = '\'this\' \i\s \"quoted\"';// goodconst foo = '\'this\' is "quoted"';const foo = `my name is '${name}'`;


原文地址:JavaScript 风格指南

-- 未完待续 --

原创粉丝点击