//longhandif(x ==='abc'|| x ==='def'|| x ==='ghi'|| x ==='jkl'){
//logic}//shorthandif(['abc','def','ghi','jkl'].includes(x)){
//logic}
三元运算符避免冗长的if else
// Longhand
let test:boolean;if(x >100){
test =true;}else{
test =false;}// Shorthand
let test =(x >10)?true:false;//or we can use directly
let test = x >10;
console.log(test);
null、undefined 和空值检查
// Longhandif(test1 !==null|| test1 !== undefined || test1 !==''){
let test2 = test1;}// Shorthand
let test2 = test1 ||'';
多变量赋值(IE不兼容)
//Longhand
let test1, test2, test3;
test1 =1;
test2 =2;
test3 =3;//Shorthand
let [test1, test2, test3]=[1,2,3];
if 判断值是否存在
// Longhandif(test1 ===true) or if(test1 !=="") or if(test1 !==null)// Shorthand //it will check empty string,null and undefined tooif(test1)
// Longhandfor(var i =0; i < testData.length; i++)// Shorthandfor(let i in testData) or for(let i of testData)
遍历数组的风骚技巧
function testData(element, index, array){
alert('test['+ index +'] = '+ element);}[11,24,32].forEach(testData);片
判断空的if else
// Longhand
let test;
function checkReturn(){
if(!(test === undefined)){
return test;}else{
returncallMe('test');}}var data =checkReturn();
console.log(data);//output test
function callMe(val){
console.log(val);}// Shorthand
function checkReturn(){
return test ||callMe('test');}
箭头函数(IE不兼容)
//Longhand
function add(a, b){
return a + b;}//Shorthand const add =(a, b)=> a + b;
风骚的根据对应值调用对应函数技巧
// Longhand
function test1(){
console.log('test1');};
function test2(){
console.log('test2');};var test3 =1;if(test3 ==1){
test1();}else{
test2();}// Shorthand(test3 ===1? test1:test2)();
避免switch的风骚技巧
// Longhandswitch(data){
case1:test1();break;case2:test2();break;case3:test();break;// And so on...}// Shorthandvar data ={
1: test1,2: test2,3: test
};
data[something]&& data[something]();
简单的字符串转数字
//Longhand var test1 =parseInt('123');var test2 =parseFloat('12.3');//Shorthand var test1 =+'123';var test2 =+'12.3';
数组find特定对象(IE不兼容)
const data =[{
type:'test1',
name:'abc'},{
type:'test2',
name:'cde'},{
type:'test1',
name:'fgh'},]
function findtest1(name){
for(let i =0; i < data.length;++i){
if(data[i].type ==='test1'&& data[i].name === name){
return data[i];}}}//Shorthand
filteredData = data.find(data => data.type ==='test1'&& data.name ==='fgh');
console.log(filteredData);// { type: 'test1', name: 'fgh' }