欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

20个JS简写技巧提升工作效率

程序员文章站 2022-06-15 15:15:09
目录当同时声明多个变量时,可简写成一行利用解构,可为多个变量同时赋值巧用三元运算符简化if else使用||运算符给变量指定默认值使用&&运算符简化if语句使用解构交换两个变量的值适用...

前言:

最近看了一些简化js代码的文章,其中有一篇觉得还不错,但是是英文的,也看了一些中文翻译,一个是一字一句翻译太生硬,没有变成自己的东西,另外就是后面作者有新增没有及时更新,于是我按照自己的语言翻译整理成此文,本文特点以言简意赅为主

当同时声明多个变量时,可简写成一行

//longhand
let x;
let y = 20;
 
//shorthand
let x, y = 20;


利用解构,可为多个变量同时赋值

//longhand
let a, b, c;

a = 5;
b = 8;
c = 12;

//shorthand
let [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时,则值为后面表达式的结果

//longhand
let imagepath;

let path = getimagepath();

if (path !== null && path !== undefined && path !== '') {
    imagepath = path;
} else {
    imagepath = 'default.jpg';
}

//shorthand
let imagepath = getimagepath() || 'default.jpg';

使用&&运算符简化if语句

例如某个函数在某个条件为真时才调用,可简写

//longhand
if (isloggedin) {
    gotohomepage();
 }

//shorthand
isloggedin && gotohomepage();


使用解构交换两个变量的值

let x = 'hello', y = 55;

//longhand
const temp = x;
x = y;
y = temp;

//shorthand
[x, y] = [y, x];

适用箭头函数简化函数

//longhand
function add(num1, num2) {
  return num1 + num2;
}

//shorthand
const add = (num1, num2) => num1 + num2;


需要注意箭头函数和普通函数的区别

使用字符串模板简化代码

使用模板字符串代替原始的字符串拼接

//longhand
console.log('you got a missed call from ' + number + ' at ' + time);

//shorthand
console.log(`you got a missed call from ${number} at ${time}`);

多行字符串也可使用字符串模板简化

//longhand
console.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.'
            );


//shorthand
console.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.`
            );


对于多值匹配,可将所有值放在数组中,通过数组方法来简写

//longhand
if (value === 1 || value === 'one' || value === 2 || value === 'two') {
  // execute some code
}

// shorthand 1
if ([1, 'one', 2, 'two'].indexof(value) >= 0) {
   // execute some code
}

// shorthand 2
if ([1, 'one', 2, 'two'].includes(value)) { 
    // execute some code 
}

巧用es6对象的简洁语法

例如:当属性名和变量名相同时,可直接缩写为一个

let firstname = 'amitav';
let lastname = 'mishra';

//longhand
let obj = {firstname: firstname, lastname: lastname};

//shorthand
let obj = {firstname, lastname};


使用一元运算符简化字符串转数字

//longhand
let total = parseint('453');
let average = parsefloat('42.6');

//shorthand
let total = +'453';
let average = +'42.6';


使用repeat()方法简化重复一个字符串

//longhand
let 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()

//longhand
const power = math.pow(4, 3); // 64

// shorthand
const power = 4**3; // 64


使用双波浪线运算符(~~)代替math.floor()

//longhand
const floor = math.floor(6.8); // 6

// shorthand
const floor = ~~6.8; // 6


需要注意,~~仅适用于小于2147483647的数字

巧用扩展操作符(...)简化代码

简化数组合并

let arr1 = [20, 30];

//longhand
let arr2 = arr1.concat([60, 80]); // [20, 30, 60, 80]

//shorthand
let arr2 = [...arr1, 60, 80]; // [20, 30, 60, 80]


单层对象的拷贝

let obj = {x: 20, y: {z: 30}};

//longhand
const 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);



//shorthand
const cloneobj = json.parse(json.stringify(obj));

//shorthand for single level object
let obj = {x: 20, y: 'hello'};
const cloneobj = {...obj};

寻找数组中的最大和最小值

// shorthand
const arr = [2, 8, 15, 4];
math.max(...arr); // 15
math.min(...arr); // 2


使用for in和for of来简化普通for循环

let arr = [10, 20, 30, 40];

//longhand
for (let i = 0; i < arr.length; i++) {
  console.log(arr[i]);
}

//shorthand
//for of loop
for (const val of arr) {
  console.log(val);
}

//for in loop
for (const index in arr) {
  console.log(arr[index]);
}


简化获取字符串中的某个字符

let str = 'jscurious.com';

//longhand
str.charat(2); // c

//shorthand
str[2]; // c


移除对象属性

let obj = {x: 45, y: 72, z: 68, p: 98};

// longhand
delete obj.x;
delete obj.p;
console.log(obj); // {y: 72, z: 68}

// shorthand
let {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];

//longhand
let filterarray = arr.filter(function(value) {
    if(value) return value;
});
// filterarray = [12, "xyz", -25, 0.5]

// shorthand
let filterarray = arr.filter(boolean);
// filterarray = [12, "xyz", -25, 0.5]

到此这篇关于20个js简写技巧提升工作效率的文章就介绍到这了,更多相关js简写技巧内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

相关标签: JS 简写 技巧