变量

优质
小牛编辑
134浏览
2023-12-01

使用有意义并且可读的变量名称

不好的:

const yyyymmdstr = moment().format('YYYY/MM/DD');

好的:

const currentDate = moment().format('YYYY/MM/DD');

为相同类型的变量使用相同的词汇

不好的:

getUserInfo();
getClientData();
getCustomerRecord();

好的:

getUser();

使用可搜索的名称

我们要阅读的代码比要写的代码多得多, 所以我们写出的代码的可读性和可搜索性是很重要的。 使用没有意义的变量名将会导致我们的程序难于理解, 将会伤害我们的读者, 所以请使用可搜索的变量名。 类似 buddy.jsESLint 的工具可以帮助我们找到未命名的常量。

不好的:

// 艹, 86400000 是什么鬼?
setTimeout(blastOff, 86400000);

好的:

// 将它们声明为全局常量 `const` 。
const MILLISECONDS_IN_A_DAY = 86400000;

setTimeout(blastOff, MILLISECONDS_IN_A_DAY);

使用解释性的变量

不好的:

const address = 'One Infinite Loop, Cupertino 95014';
const cityZipCodeRegex = /^[^,\\]+[,\\\s]+(.+?)\s*(\d{5})?$/;
saveCityZipCode(address.match(cityZipCodeRegex)[1], address.match(cityZipCodeRegex)[2]);

好的:

const address = 'One Infinite Loop, Cupertino 95014';
const cityZipCodeRegex = /^[^,\\]+[,\\\s]+(.+?)\s*(\d{5})?$/;
const [, city, zipCode] = address.match(cityZipCodeRegex) || [];
saveCityZipCode(city, zipCode);

避免心理映射

显示比隐式更好

不好的:

const locations = ['Austin', 'New York', 'San Francisco'];
locations.forEach((l) => {
  doStuff();
  doSomeOtherStuff();
  // ...
  // ...
  // ...
  // 等等, `l` 是啥?
  dispatch(l);
});

好的:

const locations = ['Austin', 'New York', 'San Francisco'];
locations.forEach((location) => {
  doStuff();
  doSomeOtherStuff();
  // ...
  // ...
  // ...
  dispatch(location);
});

不添加不必要的上下文

如果你的类名/对象名有意义, 不要在变量名上再重复。

不好的:

const Car = {
  carMake: 'Honda',
  carModel: 'Accord',
  carColor: 'Blue'
};

function paintCar(car) {
  car.carColor = 'Red';
}

好的:

const Car = {
  make: 'Honda',
  model: 'Accord',
  color: 'Blue'
};

function paintCar(car) {
  car.color = 'Red';
}

使用默认变量替代短路运算或条件

不好的:

function createMicrobrewery(name) {
  const breweryName = name || 'Hipster Brew Co.';
  // ...
}

好的:

function createMicrobrewery(breweryName = 'Hipster Brew Co.') {
  // ...
}