[点晴永久免费OA]Javascript常用的16个简写小技巧 开发效率直接翻倍
当前位置:点晴教程→点晴OA办公管理信息系统
→『 经验分享&问题答疑 』
JavaScript 是一门强大且灵活的语言,拥有丰富的特性和语法糖。分享下 16 个最常用的 JavaScript 的简写技巧,掌握它们可以让我们编写出更简洁、更优雅的代码,并显著提升开发效率。 1. 声明多个变量 常规写法: let a; let b; let c;
简写: let a, b, c;
2. If - Else 简写 常规 if - else : let num = 10; let result; if (num > 5) { result = '大于5'; } else { result = '小于等于5'; }
三元运算符简写: let num = 10; let result = num > 5? '大于5' : '小于等于5';
3. && 短路求值 常规写法: let message; let condition = true; if (condition) { message = '条件为真'; }
简写: let condition = true; let message = condition && '条件为真';
4. || 短路求值 常规写法: let value; let someValue = null; if (someValue) { value = someValue; } else { value = '默认值'; }
简写: let someValue = null; let value = someValue || '默认值';
5. 对象属性简写 常规写法: let name = 'John'; let age = 30; let person = { name: name, age: age };
简写: let name = 'John'; let age = 30; let person = { name, age };
6. 对象方法简写 常规写法: let obj = { method: function () { console.log('方法执行'); } };
简写: let obj = { method() { console.log('方法执行'); } };
7. 箭头函数 常规函数: function add(a, b) { return a + b; }
箭头函数简写: const add = (a, b) => a + b;
8. 数组解构赋值 常规写法: let arr = [1, 2]; let a = arr[0]; let b = arr[1];
简写: javascript let [a, b] = [1, 2];
9. 对象解构赋值 常规写法: let person = { name: 'John', age: 30 }; let name = person.name; let age = person.age;
简写: let { name, age } = { name: 'John', age: 30 };
10. 扩展运算符(数组) 合并数组常规写法: let arr1 = [1, 2]; let arr2 = [3, 4]; let combined = arr1.concat(arr2);
扩展运算符简写: let arr1 = [1, 2]; let arr2 = [3, 4]; let combined = [...arr1,...arr2];
11. 扩展运算符(对象) 合并对象常规写法: let obj1 = { a: 1 }; let obj2 = { b: 2 }; let merged = Object.assign({}, obj1, obj2);
扩展运算符简写: let obj1 = { a: 1 }; let obj2 = { b: 2 }; let merged = {...obj1,...obj2 };
12. for...of 循环遍历数组 for 循环常规写法: let arr = [1, 2, 3]; for (let i = 0; i < arr.length; i++) { console.log(arr[i]); }
for...of 简写: let arr = [1, 2, 3]; for (let num of arr) { console.log(num); }
13. 数组 map 方法创建新数组 常规 for 循环创建新数组: let arr = [1, 2, 3]; let newArr = []; for (let i = 0; i < arr.length; i++) { newArr.push(arr[i] * 2); }
map 方法简写: let arr = [1, 2, 3]; let newArr = arr.map(num => num * 2);
14. 数组 filter 方法过滤数组 常规 for 循环过滤数组: let arr = [1, 2, 3, 4, 5]; let filteredArr = []; for (let i = 0; i < arr.length; i++) { if (arr[i] > 3) { filteredArr.push(arr[i]); } }
filter 方法简写: let arr = [1, 2, 3, 4, 5]; let filteredArr = arr.filter(num => num > 3);
15. 指数运算 常规写法: let result = Math.pow(2, 3);
指数运算符简写: let result = 2 ** 3;
16. 模板字面量 常规字符串拼接: let name = 'John'; let greeting = 'Hello, ' + name + '!';
模板字面量简写: let name = 'John'; let greeting = `Hello, ${name}!`; 该文章在 2025/1/7 12:33:05 编辑过 |
关键字查询
相关文章
正在查询... |