1. include方法代替多条件if语句
// bad
if (x === "abc" || x === "def" || x === "ghi" || x === "jkl") {}
// better
if (["abc", "def", "ghi", "jkl"].includes(x)) {}
2. 三元代替if else
// bad
if (x > 100) {
test = true;
} else {
test = false;
}
// better
let test = x > 10 ? true : false;
//or
let test = x > 10;
3. 假值(null,undefined,'',0,false,NaN)检查
仅当左侧为空或 NaN 或 null 或 undefined 或 false 时,如果左侧操作数为假,则将返回右侧操作数,逻辑或运算符 (||) 将返回右侧的值。
// bad
if (test1 !== null || test1 !== undefined || test1 !== "") {
let test2 = test1;
}
// better
let test2 = test1 || "";
4. null/undefined检查和默认赋值
仅当左侧为null 或 undefined,则将返回右侧操作数
let test1 = null;
let test2 = test1 ?? "";
console.log(test2); // ""
const test = undefined ?? "default";
console.log(test); // "default"
5. 获取列表中的最后一项
slice方法可从已有的数组或者字符串返回选定的元素。 语法:arr.slice(开始位置,结束位置) 左闭右开,返回值是数组的子数组,不会改变原数组,如果想删除原数组的一段元素,可以使用arr.splice(开始索引,删除的个数,新值) 开始位置必填,如果开始位置是负数则从数组尾部算起,-1就是最后一位。 结束位置选填,如果不填默认到数组结尾,如果是负数默认数组尾部算起。
let array = [0, 1, 2, 3, 4, 5, 6, 7];
console.log(array.slice(-1)) >>> [7];
console.log(array.slice(-2)) >>> [6, 7];
console.log(array.slice(-3)) >>> [5, 6, 7];
function lastItem(list) {
if (Array.isArray(list)) {
return list.slice(-1)[0];
}
if (list instanceof Set) {
return Array.from(list).slice(-1)[0];
}
if (list instanceof Map) {
return Array.from(list.values()).slice(-1)[0];
}
}
6. 比较后返回
// bad
let test;
function checkReturn() {
if (!(test === undefined)) {
return test;
} else {
return callMe("test");
}
}
// better
function checkReturn() {
return test ?? callMe("test");
}
7. 使用可选链
? 也称为链判断运算,它允许开发人员读取深度嵌套在对象链中的属性值,而无需验证每个引用,当引用为空时,表达式停止计算并返回 undefined
// bad
const res = travelPlans && travelPlans.tuesday && travelPlans.tuesday.location && travelPlans.tuesday.location.href;
console.log(res); // Result: undefined
// better
const res1 = travelPlans?.tuesday?.location?.href;
console.log(res1); // Result: undefined
8. 多条件的&&运算符
要仅在变量为真时调用函数,请使用 && 运算符。
// bad
if (test) {
callMethod();
}
// better
test && callMethod();
9. 简化swtich语法
我们可以将条件存储在键值对象中,并根据条件调用它们。
// bad
switch (data) {
case 1:
test1();
break;
case 2:
test2();
break;
case 3:
test();
break;
// And so on...
}
// better
var data = {
1: test1,
2: test2,
3: test,
};
10. 默认参数
function add(test1, test2) {
if (test1 === undefined) test1 = 1;
if (test2 === undefined) test2 = 2;
return test1 + test2;
}
// better
add = (test1 = 1, test2 = 2) => test1 + test2;
11. 对象属性赋值
let test1 = "a";
let test2 = "b";
// bad
let obj = { test1: test1, test2: test2 };
// better
let obj = { test1, test2 };
12. 解构赋值
// bad
const test1 = this.data.test1;
const test2 = this.data.test2;
const test2 = this.data.test3;
// better
const { test1, test2, test3 } = this.data;
13. 模板字符串
模板字符串允许你在字符串里使用变量,格式为${变量},并且能保持换行等格式
// bad
const welcome = "Hi " + test1 + " " + test2 + ".";
// better
const welcome = `Hi ${test1} ${test2}`;
// bad
const data ="hello maxwell this is a test\n\t" + "test test,test test test test\n\t";
// better
const data = `hello maxwell this is a test
test test,test test test test`;
14. indexOf的按位简化
// bad
if (arr.indexOf(item) > -1) {
// item found
}
if (arr.indexOf(item) === -1) {
// item not found
}
// better
if (~arr.indexOf(item)) {
// item found
}
if (!~arr.indexOf(item)) {
// item not found
}
15. 字符串转数字
有诸如 parseInt 和 parseFloat 等内置方法可用于将字符串转换为数字。我们也可以简单地通过在字符串前面提供一元运算符 (+) 来做到这一点。
// bad
let total = parseInt("583");
let average = parseFloat("32.5");
// better
let total = +"583";
let average = +"32.5";
16. 带范围的随机数生成器
有时你需要生成随机数,但又希望数字在一定范围内,则可以使用此工具。
function randomNumber(max = 1, min = 0) {
if (min >= max) {
return max;
}
return Math.floor(Math.random() * (max - min) + min);
}
生成随机颜色
function getRandomColor() {
const colorAngle = Math.floor(Math.random() * 360);
return `hsla(${colorAngle},100%,50%,1)`;
}
17. async, await
异步函数是使用 async 关键字声明的函数,并且允许在其中使用 await 关键字。async 和 await 关键字使异步的、基于 Promise 的行为能够以更简洁的方式编写,避免了显式配置 Promise 链的需要。
async test() {
try {
const result = await otherAsyncFunction();
console.log(result); // output result
} catch(e) {
console.log(e); // Can catch errors if otherAsyncFunction() throws an error
}
}
18. Object.values()和Object.keys()
const exampleObj = {a: 1, b: 2, c: 3, d:4};
console.log(Object.value(exampleObj)); // [1, 2, 3, 4];返回对象自身属性的所有值,不包括继承的值。
console.log(Object.keys(exampleObj)); // [a, b,c, d];返回对象自身属性。
19. 字符串 padStart() & padEnd()
你可以在字符串的开头或结尾添加其他内容,并将其填充到指定的长度。例如“补零”
// padStart
'100'.padStart(5, 0); // 00100
// If the content to be padded exceeds the "padding length". Then fill in from the left to the upper limit of the length
'100'.padStart(5, '987'); // 98100
// padEnd
'100'.padEnd(5, 9); // 10099
// If the content to be padded exceeds the "padding length". Then fill in from the right to the upper limit of the length
'100'.padStart(5, '987'); // 10098
内容整合自“大前端私房菜”公众号,如有侵权联系删除,更多内容可看 mp.weixin.qq.com/s/5_1SJSqoH…