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 代码简化常用写法】
推荐阅读
- 两行代码激活windows
- this对象的理解及JavaScript中执行上下文和执行栈是什么?
- 一文读懂 Android 系统的源代码
- VSCode疑案:Go代码智能提示咋没了呢?
- 原生javascript解锁恶心的CSDN强制关注才能阅读让文章自动展开
- 格兰仕空调显示F6怎么回事什么故障 格兰仕空调故障代码
- js是什么意思?
- 教育部提醒查不到代码的都是虚假大学-考生警惕“虚假大学”
- node-xlsx 简单几行代码处理导入导出 excel 数据,免费开源的 js 库
- 专业代码在哪里查询?
