根据条件给变量赋值布尔值
// bad
if(arr.includes("xxx")){
has = true;
}else {
has = false;
}
// good
has = arr.includes("xxx");
根据数组有无内容做什么
// bad
if(arr.length !== 0){
// todo
}
if(arr.length == 0){
// todo
}
// good
if(arr.length){
// todo
}
if(!arr.length){
// todo
}
单变量多可能值判断
// bad
if(a == 1 || a == 2 || a == 3 || a == 4){
// todo
}
// good
var arr = [1,2,3,4];
if(arr.includes(a)){
// todo
}
快速获取所有对象的属性名或者属性值
var obj = {
name: "obj",
age: 212,
tel: "123342"
};
// 获取对象的属性名组成的数组
Object.getOwnPropertyNames(obj); // ["name", "age", "tel"]
Object.keys(obj); // ["name", "age", "tel"]
// 获取对象的属性值组成的数组
Object.values(obj); // ["obj", 212, "123342"]
解构赋值进行变量替换
var a = 10, b = 20;
// bad
var temp = a;
a = b;
b = temp;
// good
[b, a] = [a, b];
解构简化函数参数长属性名
// bad
setForm (data) {
this.one = data.user_info_detail_name;
this.two = data.address_detail_name;
}
// good
setForm ({user_info_detail_name, address_detail_name}) {
this.one = user_info_detail_name;
this.two = address_detail_name;
}
// best
setForm ({user_info_detail_name: one, address_detail_name: two}) {
this.one = one;
this.two = two;
}
对象中的可选属性
const obj = {
a: "whatever"
}
if(b){
obj.c = "ok";
}
// best
const obj = {
a: "whatever",
...(b && { c: "ok" })
}
函数默认值
// bad
function sum(a, b){
if(a === undefined){
a = 0;
}
if(b === undefined){
b = 0;
}
}
// good
function sum(a, b){
a = a || 0;
b = b || 0;
}
// best
function sum(a = 0, b = 0){
}
调用对象的属性的属性
有时候可能对象的属性不是一个对象,直接获取就会报错,需要验证有值
var user = {
name: "李白"
friend: {
name: "杜甫"
}
}
// bad
var friendName = user.friend.name
// good
var friendName = user.friend && user.friend.name
函数参数校验
function(a, b){
if(!a){
throw new Error("请传入必要的参数");
}
}
// good
function checkNull(){
throw new Error("请传入必要的参数");
}
function(a = checkNull(), b){
}
计算字符串中某个字符的出现次数
const charTotals = arr => arr.reduce((totals, char) => ({
...totals, [char]: (totals[char] || 0) + 1
}), {})
charTotals("happy".split(""));
// "h":1,"a":1,"p":2,"y":1