变量

13.1 经常使用constlet来声明变量。不这样做将会导致全局变量。我们希望能避免污染全局命名空间。地球队长警告我们的。(译注:global也有全球的意思,这里是一个双关语)

eslint: no-undef prefer-const

// bad
superPower = new SuperPower();

// good
const superPower = new SuperPower();

13.2 每个变量都使用一次const或者let声明

eslint: one-var jscs: disallowMultipleVarDecl

为什么?这样可以更容易的添加新的变量,而且你永远不用担心把;,混淆(深有体会。。。),或者引入标点符号差异。你也可以使用debugger来调试每一步,而不是一下子跳过了它们

// bad
const items = getItems(),
    goSportsTeam = true,
    dragonball = 'z';

// bad
// (compare to above, and try to spot the mistake)
const items = getItems(),
    goSportsTeam = true;
    dragonball = 'z';

// good
const items = getItems();
const goSportsTeam = true;
const dragonball = 'z';

13.3 将所有的constlet分组

为什么?这在你后面把一个已赋值变量赋值给一个未赋值变量的时候非常有用

// bad
let i, len, dragonball,
    items = getItems(),
    goSportsTeam = true;

// bad
let i;
const items = getItems();
let dragonball;
const goSportsTeam = true;
let len;

// good
const goSportsTeam = true;
const items = getItems();
let dragonball;
let i;
let length;

13.4 当你需要的时候就声明变量,但是把它们放到合适的位置

为什么?letconst是块作用域而不是函数作用域

// bad - unnecessary function call
function checkName(hasName) {
  const name = getName();

  if (hasName === 'test') {
    return false;
  }

  if (name === 'test') {
    this.setName('');
    return false;
  }

  return name;
}

// good
function checkName(hasName) {
  if (hasName === 'test') {
    return false;
  }

  const name = getName();

  if (name === 'test') {
    this.setName('');
    return false;
  }

  return name;
}

13.5 不要链式声明变量

eslint: no-multi-assign

为什么?链式变量声明会创建隐式的全局变量

// bad
(function example() {
  // JavaScript interprets this as
  // let a = ( b = ( c = 1 ) );
  // The let keyword only applies to variable a; variables b and c become
  // global variables.
  let a = b = c = 1;
}());

console.log(a); // throws ReferenceError
console.log(b); // 1
console.log(c); // 1

// good
(function example() {
  let a = 1;
  let b = a;
  let c = a;
}());

console.log(a); // throws ReferenceError
console.log(b); // throws ReferenceError
console.log(c); // throws ReferenceError

// the same applies for `const`

13.6 避免使用一元运算符++--

eslint: no-plusplus

为什么?根据eslint文档,一元递增和递减语句会受到自动分号插入的影响,并且会在应用程序中增加或减少值时导致无提示错误。用像num + = 1而不是num++num ++这样的语句改变你的值也是更具表现力的。不允许一元递增和递减语句也会阻止无意中预先递增/预递减值,这也会导致程序中的意外行为。

// bad

const array = [1, 2, 3];
let num = 1;
num++;
--num;

let sum = 0;
let truthyCount = 0;
for (let i = 0; i < array.length; i++) {
  let value = array[i];
  sum += value;
  if (value) {
    truthyCount++;
  }
}

// good

const array = [1, 2, 3];
let num = 1;
num += 1;
num -= 1;

const sum = array.reduce((a, b) => a + b, 0);
const truthyCount = array.filter(Boolean).length;

results matching ""

    No results matching ""