关于javascript:20个提升效率的JS简写技巧

33次阅读

共计 4116 个字符,预计需要花费 11 分钟才能阅读完成。

注释
简写技巧
当同时申明多个变量时,可简写成一行
//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]
复制代码
THE END
文章(除了代码)都是以自己本人的语言组织,且有删减

注释局部的代码,Longhand 示意惯例写法,Shorthand 示意简写模式

以上就是本文的所有内容,如有问题欢送留言🌹~

最初
如果你感觉此文对你有一丁点帮忙,点个赞。或者能够退出我的开发交换群:1025263163 互相学习,咱们会有业余的技术答疑解惑

如果你感觉这篇文章对你有点用的话,麻烦请给咱们的开源我的项目点点 star: https://gitee.com/ZhongBangKe… 不胜感激!

PHP 学习手册:https://doc.crmeb.com/
技术交换论坛:https://q.crmeb.com/

正文完
 0