Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JavaScript变量代码简洁可读性 #7

Open
LiZheGuang opened this issue Nov 5, 2019 · 0 comments
Open

JavaScript变量代码简洁可读性 #7

LiZheGuang opened this issue Nov 5, 2019 · 0 comments

Comments

@LiZheGuang
Copy link
Owner

JavaScript变量代码简洁可读性

使用有意义且明显的变量名

// Bad:
const yyyymmdstr = moment().format("YYYY/MM/DD");

// Good:
const currentDate = moment().format("YYYY/MM/DD");

对相同类型的变量使用相同的词汇表

// Bad:
getUserInfo();
getClientData();
getCustomerRecord();

// Good:
getUser();

使用可搜索的名称

// Bad:
setTimeout(blastOff, 86400000);

// Good:
const MILLISECONDS_IN_A_DAY = 86400000;

setTimeout(blastOff, MILLISECONDS_IN_A_DAY);

使用解释变量

// Bad:

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

// Good:

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

避免没有语义化的行为

显式胜于隐式

// Bad:

const locations = ["Austin", "New York", "San Francisco"];
locations.forEach(l => {
  doStuff();
  doSomeOtherStuff();
  // ...
  // ...
  // ...
  // l 是个什么?
  dispatch(l);
});

// Good:

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

不要添加不需要的上下文

如果你的类或者对象名称告诉您某些内容,请不要在变量名称中重复。

// Bad:

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

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

// Good:

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

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

使用默认参数代替有条件的判断

默认参数通常比判断更干净。请注意,如果使用它们,则函数将仅提供未定义参数的默认值。其他“虚假”值(例如”,“”,false,null,0和NaN)将不会替换为默认值。

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

// Good:
function createMicrobrewery(name = "Hipster Brew Co.") {
  // ...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant