对于前端来说,JS简写可以帮助写出更加简练优化的代码,并且还可以在少写代码的基础上达成目标,那么就简单记录一下平时常用的一些小小干货吧
一:声明变量
1 // normal 2 let x; 3 let y=10; 4 5 // concise 6 let x,y=10;
二:将多个变量赋值
我们可以通过数组解构来对一行中的多个变量赋值
// normal let a,b,c; a=1; b=2; c=3; // concise let [a,b,c]=[1,2,3];
三:三元运算符
通过三元运算符,我们可以在一些地方更简洁明了的实现效果
// normal let Num=10; let result; if(Num>=20){ result='ok'; }else{ result='no'; } // concise let result=Num>=20?'ok':'no';
四:分配默认值
如果期望值不正确,我们可以使用OR(丨丨)短路运算,为变量分配默认值
// normal let filePath; let path=getFilePath(); if (path!==null&&path!==undefined&&path!=='') { filePath=path; } else{ filePath='defaultPath'; } // concise let filePath=getFilePath()||'defaultPath';
五:与(&&)短路运算
如果仅在变量为true的情况下调用函数,你就可以使用与(&&)的短路形式作为替代方法
// normal if(isLogin){ goToHomePage(); } // concise isLogin&&goToHomePage();
在react中,当你想要有条件的渲染组件时,与(&&)短路写法更加实用。比如:
<div>{this.state.isLogin&&<Home />}</div>
六:交换两个变量
交换两个变量的时候,我们经常会用到第三个变量。我们可以通过解构任务来轻松交换两个变量
let x='Hello World',y=10; // normal const temp=x; x=y; y=temp; // concise [x,y]=[y,x]
七:箭头函数
// normal function add(num1,num2){ return num1+num2; } // concise const add=(num1,num2)=>num1+num2;
八:模板字符串
我们通常运用“+”运算符连接字符串变量。通过使用ES6的模板,我们可以用更简单的方法进行处理
// normal console.log('You got a miss call from '+number+'at'+time); // concise console.log(`You got a miss call from ${number} at ${time}`);
九:多行字符串
对于多行字符串,我们通常将“+”运算符与(\n)配合使用。我们可以通过(``)的方法更加轻松的实现它
// normal console.log('JavaScript is a programming language that belongs to HTML and web.\n'+ 'Programming enables computers to do what you need them to do.\n'+ 'JavaScript is easy to learn.'); // concise console.log(`JavaScript is a programming language that belongs to HTML and web. Programming enables computers to do what you need them to do. JavaScript is easy to learn.`);
十:多条件检查
对于多值匹配来说,我们可以把所有的值都放在数组中,并且采用indexOf()或includes()的方法
// normal if(value===1||value==='one'||value===2||value==='two'){ // do some thing } // concise1 if([1,'one',2,'two'].indexOf(value)>=0){ // do some thing } // concise2 if([1,'one',2,'two'].includes(value)){ // do some thing }
十一:对象属性复制
如果变量名称和对象属性名相同,那么我们可以在目标文字中仅提到变量名称就可以,而不是两个都提到。JavaScript会自动将关键对象名称设置为变量名称,并将该值分配为变量值
let fristName='Ed'; let fristName='Nick'; // normal let obj={fristName:fristName,fristName:fristName}; // concise let obj={fristName,fristName};
十二:字符串转变为数字
我们可以通过parseInt和parseFloat的方法将字符串转变为数字,也可以通过一下这种简单的方法——将一元运算符“+”置于字符串值之前
// normal let total=parseInt('20'); let average=parseFloat('40.5'); // concise let total=+'20'; let average=+'40.5';
十三:多次重复一个字符串
想要将一个字符串重复具体的次数,你可以使用for循环。但使用repeat()的方法,我们可以在一行代码之内将它完成
// normal let str=''; for(let i=0;i<5;i++){ str +='Hello World'; } console.log(str); //Hello World Hello World Hello World Hello World Hello World // concise 'Hello World'.repeat(5)
十四:指数幂
我们可以使用Math.pow()的方法查找数字的幂,但下面这个方法可以让你使用更短的代码——两个(**)即可
// normal const power=Math.pow(4,3); //64 // concise const power=4**3; //64
十五:双非位运算符(~~)
双非位运算符(~~)是Math.floor()方法的缩写
// normal const floor=Math.floor(6.8); //6 // concise const floor=~~6.8; //6
补充说明:(~~)仅适用于32位整数,即(2** 31)-1=2147483647。因此,对于大于2147483647的任何数字,按位运算符(~~)将给出错误的结果,所以在这种情况下建议使用Math.floor()。
十六:在数组中发现最大值和最小值
我们可以使用for循环在查找数组中的每一个值,并且找到最大值和最小值,也可以通过使用Array.reduce()的方法来查找最大值和最小值。但是使用扩展符号,我们可以在一行之内搞定
// concise const arr=[1,2,3,4,5]; Math.max(...arr) //5 Math.min(...arr) //1
十七:For循环
想要遍历数组,我们通常都会使用传统的for循环,可以使用for...of循环来遍历数组。想要访问每个值的索引,我们可以使用for...in循环
// normal for(let i=0;i<arr.length;i++){ console.log(arr[i]); } // concise // for of loop for(const val of arr){ console.log(val); } // for in loop for(const index of arr){ console.log(`index:${index} and value:${arr[index]}`); }
也可以通过for...in循环遍历对象属性
let obj = {x:1,y:2};
for(const key in obj){
console.log(obj[key]);
}
十八:合并数组
let arr1=[1,2]; // normal let arr2=arr1.concat([3,4]); //[1,2,3,4] // concise let arr2=[...arr1,3,4]; //[1,2,3,4]
十九:深拷贝多级对象
如果要深拷贝多级对象,我们要遍历每个属性并检查当前属性是否包含对象。如果是,则通过传递当前属性值(即嵌套对象)对同一函数进行递归调用
如果我们的对象不包括函数,undefined,NaN或Date作为值的话,我们也可以通过使用JSON.stringify()和JSON.parse()的方法执行以上操作
如果我们有单层对象,也就是不存在嵌套对象,那么我们也可以使用扩展符进行深拷贝
const obj={x:1,y:{z:2}};
// normal
const makeDeepClone=(obj)=>{
let newObject={};
Object.key(obj).map(key=>{
if(typeof obj[key]==='object'){
newObject[key]=makeDeepClone(obj[key]);
}else{
newObject[key]=obj[key];
}
});
return newObject;
}
const cloneObj=makeDeepClone(obj);
// concise
const cloneObj=JSON.parse(JSON.stringify(obj));
// concise for single level object
let obj = {x:1,y:'Hello World'};
const cloneObj=(...obj);
补充说明:如果你的对象属性包括function,undefined或者NaN作为值,那么JSON.parse(JSON.stringify(obj))的简写技巧并不适用。因为当使用JSON.stringify对象时,属性包括function,undefined或者NaN作为值就会从对象中移除。
所以,当你的对象中仅包含字符串和数字时,你可以使用JSON.parse(JSON.stringify(obj))。
二十:从字符串中获取字符
let str = 'happy.com' // normal str.charAt(2); //p // concise str[2]; //p

浙公网安备 33010602011771号