Javascript 代码简化常用写法

1、利用“或”(||)短路逻辑,给变量赋值 。
// a应该是一个有意义的字符串,不能说null,undefined,nullconst getData = https://www.isolves.com/it/cxkf/yy/js/2022-07-04/(a) => {// let b = "";// if (a !== null || a !== undefined || a !== false) {//b = a;//}// 简化let b = a || "";};2、利用箭头函数简化函数
// 求两个数的和// const sum = function (a, b) {//return a + b;// };// 简化 const sum = (a, b) => a + b;3、利用三元运算符号简化if else
const difNum = (a, b) => {// let res;// if (a > b) {//res = a - b;// } else {//res = b - a;// }// return res;// 简化return a > b ? a - b : b - a;};4、利用ES6对象解构简化
const data = https://www.isolves.com/it/cxkf/yy/js/2022-07-04/{a: 1,b: 2,c: 3,d: 4,e: 5,f: 6,};const sum = (data) => {// const a = data.a,//b = data.b,//c = data.c;// 简化const { a, b, c } = data;};5、利用数组中元素检测进行条件判断
const isShow = (a) => {// let res = false;// if (a === "你好") {//res = true;// }// if (a === "你好啊") {//res = true;// }// if (a === "哈喽") {//res = true;// }// if (a === "hello") {//res = true;// }// if (a === "嗨") {//res = true;// }// return res// 简化const hello = ["你好", "你好啊", "哈喽", "hello", "嗨"];return hello.indexOf(a) > -1;};6、利用ES6中的模板字符串生产字符串
const sethtml = (a, b, c) => {// let str = "<div>" + a + "<div>";// str += "<div>" + b + "<div>";// str += "<div>" + c + "<div>";// 简化let str = `<div>${a}</div><div>${b}</div><div>${c}</div>`;return str;};其他还有很多代码简化的方法,希望大家发出来交流,敲代码的时候少打点字

【Javascript 代码简化常用写法】


    推荐阅读