提升效率的JavaScript简写技巧有哪些
这篇文章主要讲解了"提升效率的JavaScript简写技巧有哪些",文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习"提升效率的JavaScript简写技巧有哪些"吧!
简写技巧
当同时声明多个变量时,可简写成一行
//Longhandlet x;let y = 20; //Shorthandlet x, y = 20;
利用解构,可为多个变量同时赋值
//Longhandlet a, b, c;a = 5;b = 8;c = 12;//Shorthandlet [a, b, c] = [5, 8, 12];
巧用三元运算符简化if else
//Longhand let marks = 26; let result; if (marks >= 30) { result = 'Pass'; } else { result = 'Fail'; } //Shorthand let result = marks >= 30 ? 'Pass' : 'Fail';
使用||运算符给变量指定默认值
本质是利用了||运算符的特点,当前面的表达式的结果转成布尔值为false时,则值为后面表达式的结果
//Longhandlet imagePath;let path = getImagePath();if (path !== null && path !== undefined && path !== '') { imagePath = path;} else { imagePath = 'default.jpg';}//Shorthandlet imagePath = getImagePath() || 'default.jpg';
使用&&运算符简化if语句
例如某个函数在某个条件为真时才调用,可简写
//Longhandif (isLoggedin) { goToHomepage(); }//ShorthandisLoggedin && goToHomepage();
使用解构交换两个变量的值
let x = 'Hello', y = 55;//Longhandconst temp = x;x = y;y = temp;//Shorthand[x, y] = [y, x];
适用箭头函数简化函数
//Longhandfunction add(num1, num2) { return num1 + num2;}//Shorthandconst add = (num1, num2) => num1 + num2;
需要注意箭头函数和普通函数的区别
使用字符串模板简化代码
使用模板字符串代替原始的字符串拼接
//Longhandconsole.log('You got a missed call from ' + number + ' at ' + time);//Shorthandconsole.log(`You got a missed call from ${number} at ${time}`);
多行字符串也可使用字符串模板简化
//Longhandconsole.log('JavaScript, often abbreviated as JS, is a\n' + 'programming language that conforms to the \n' + 'ECMAScript specification. JavaScript is high-level,\n' + 'often just-in-time compiled, and multi-paradigm.' );//Shorthandconsole.log(`JavaScript, often abbreviated as JS, is a programming language that conforms to the ECMAScript specification. JavaScript is high-level, often just-in-time compiled, and multi-paradigm.` );
对于多值匹配,可将所有值放在数组中,通过数组方法来简写
//Longhandif (value === 1 || value === 'one' || value === 2 || value === 'two') { // Execute some code}// Shorthand 1if ([1, 'one', 2, 'two'].indexOf(value) >= 0) { // Execute some code}// Shorthand 2if ([1, 'one', 2, 'two'].includes(value)) { // Execute some code }
巧用ES6对象的简洁语法
例如,当属性名和变量名相同时,可直接缩写为一个
let firstname = 'Amitav';let lastname = 'Mishra';//Longhandlet obj = {firstname: firstname, lastname: lastname};//Shorthandlet obj = {firstname, lastname};
使用一元运算符简化字符串转数字
//Longhandlet total = parseInt('453');let average = parseFloat('42.6');//Shorthandlet total = +'453';let average = +'42.6';
使用repeat()方法简化重复一个字符串
//Longhandlet str = '';for(let i = 0; i < 5; i ++) { str += 'Hello ';}console.log(str); // Hello Hello Hello Hello Hello// Shorthand'Hello '.repeat(5);// 想跟你说100声抱歉!'sorry\n'.repeat(100);
使用双星号代替Math.pow()
//Longhandconst power = Math.pow(4, 3); // 64// Shorthandconst power = 4**3; // 64
使用双波浪线运算符(~~)代替Math.floor()
//Longhandconst floor = Math.floor(6.8); // 6// Shorthandconst floor = ~~6.8; // 6
需要注意,~~仅适用于小于2147483647的数字
巧用扩展操作符(...)简化代码
简化数组合并
let arr1 = [20, 30];//Longhandlet arr2 = arr1.concat([60, 80]); // [20, 30, 60, 80]//Shorthandlet arr2 = [...arr1, 60, 80]; // [20, 30, 60, 80]
单层对象的拷贝
let obj = {x: 20, y: {z: 30}};//Longhandconst makeDeepClone = (obj) => { let newObject = {}; Object.keys(obj).map(key => { if(typeof obj[key] === 'object'){ newObject[key] = makeDeepClone(obj[key]); } else { newObject[key] = obj[key]; }});return newObject;}const cloneObj = makeDeepClone(obj);//Shorthandconst cloneObj = JSON.parse(JSON.stringify(obj));//Shorthand for single level objectlet obj = {x: 20, y: 'hello'};const cloneObj = {...obj};
寻找数组中的最大和最小值
// Shorthandconst arr = [2, 8, 15, 4];Math.max(...arr); // 15Math.min(...arr); // 2
使用for in和for of来简化普通for循环
let arr = [10, 20, 30, 40];//Longhandfor (let i = 0; i < arr.length; i++) { console.log(arr[i]);}//Shorthand//for of loopfor (const val of arr) { console.log(val);}//for in loopfor (const index in arr) { console.log(arr[index]);}
简化获取字符串中的某个字符
let str = 'jscurious.com';//Longhandstr.charAt(2); // c//Shorthandstr[2]; // c
移除对象属性
let obj = {x: 45, y: 72, z: 68, p: 98};// Longhanddelete obj.x;delete obj.p;console.log(obj); // {y: 72, z: 68}// Shorthandlet {x, p, ...newObj} = obj;console.log(newObj); // {y: 72, z: 68}
使用arr.filter(Boolean)过滤掉数组成员的值falsey
let arr = [12, null, 0, 'xyz', null, -25, NaN, '', undefined, 0.5, false];//Longhandlet filterArray = arr.filter(function(value) { if(value) return value;});// filterArray = [12, "xyz", -25, 0.5]// Shorthandlet filterArray = arr.filter(Boolean);// filterArray = [12, "xyz", -25, 0.5]
感谢各位的阅读,以上就是"提升效率的JavaScript简写技巧有哪些"的内容了,经过本文的学习后,相信大家对提升效率的JavaScript简写技巧有哪些这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是,小编将为大家推送更多相关知识点的文章,欢迎关注!