JavaScript 风格指南(2)

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


四、Arrays


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

// bad
const items = new Array();

// good
const items = [];

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

const someStack = [];

// bad
someStack[someStack.length] = 'abracadabra';

// good
someStack.push('abracadabra');

· 4.3 使用 ... 拷贝数组

// bad
const len = items.length;
const itemsCopy = [];
let i;

for (i = 0; i < len; i += 1) {
  itemsCopy[i] = items[i];
}

// good
const 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);

// bad
const flat = {};
[[0, 1], [2, 3], [4, 5]].reduce((memo, item, index) => {
  const flatten = memo.concat(item);
  flat[index] = flatten;
});

// good
const flat = {};
[[0, 1], [2, 3], [4, 5]].reduce((memo, item, index) => {
  const flatten = memo.concat(item);
  flat[index] = flatten;
  return flatten;
});

// bad
inbox.filter((msg) => {
  const { subject, author } = msg;
  if (subject === 'Mockingbird') {
    return author === 'Harper Lee';
  } else {
    return false;
  }
});

// good
inbox.filter((msg) => {
  const { subject, author } = msg;
  if (subject === 'Mockingbird') {
    return author === 'Harper Lee';
  }

  return false;
});

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

// bad
const arr = [
  [0, 1], [2, 3], [4, 5],
];

const objectInArray = [{
  id: 1,
}, {
  id: 2,
}];

const numberInArray = [
  1, 2,
];

// good
const arr = [[0, 1], [2, 3], [4, 5]];

const objectInArray = [
  {
    id: 1,
  },
  {
    id: 2,
  },
];

const numberInArray = [
  1,
  2,
];


五、Destructuring


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


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

  return `${firstName} ${lastName}`;
}

// good
function getFullName(user) {
  const { firstName, lastName } = user;
  return `${firstName} ${lastName}`;
}

// best
function getFullName({ firstName, lastName }) {
  return `${firstName} ${lastName}`;
}

· 5.2 使用数组解构

const arr = [1, 2, 3, 4];

// bad
const first = arr[0];
const second = arr[1];

// good
const [first, second] = arr;

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


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

// bad
function processInput(input) {
  // then a miracle occurs
  return [left, right, top, bottom];
}

// 使用者得考虑返回值的顺序 
const [left, __, top] = processInput(input);

// good
function processInput(input) {
  // then a miracle occurs
  return { left, right, top, bottom };
}

// 使用者想用什么值直接用就好了 
const { left, top } = processInput(input);

六、Strings


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

// bad
const name = "Capt. Janeway";

// bad - template literals should contain interpolation or newlines
const name = `Capt. Janeway`;

// good
const name = 'Capt. Janeway';

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


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

// bad
const 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.';

// good
const 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 当需要程序构建字符串时,请使用模板字符串,而不是字符串连接符


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

// bad
function sayHi(name) {
  return ['How are you, ', name, '?'].join();
}

// bad
function sayHi(name) {
  return `How are you, ${ name }?`;
}

// good
function sayHi(name) {
  return `How are you, ${name}?`;
}

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


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


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

// good
const foo = '\'this\' is "quoted"';
const foo = `my name is '${name}'`;


原文地址: JavaScript 风格指南

-- 未完待续 --

猜你喜欢

转载自blog.csdn.net/ghostlpx/article/details/76271028