![0e8e1f03a6506c96778286fa72a57259.png](https://i-blog.csdnimg.cn/blog_migrate/f79ec91f2cef36990dc0403b5908bd35.png)
全文共4545字,预计学习时长12分钟
![38362959f925fb080da56190771019a2.png](https://i-blog.csdnimg.cn/blog_migrate/427759871d4841dac077f4e38a2533d4.png)
无论是哪个编程语言的速记技巧,都有助于你编写更好、更清晰的代码。借助速记技巧,不仅可以提升代码可读性,还可以编写更少代码完成任务。下面是一些JavaScript的速记技巧。
1.声明变量
//Longhand
let x;
let y = 20;
//Shorthand
let x, y = 20;
2.给多个变量赋值
可以在一行代码中给多个变量同时赋值。
//Longhand
let marks = 26;
let result;
if(marks >= 30){
result = 'Pass';
}else{
result = 'Fail';
}
//Shorthand
let result = marks >= 30 ? 'Pass' : 'Fail';
3.三元运算符
使用三元运算符(条件),五行代码可以简化为一行。
//Longhand
let imagePath;
let path = getImagePath();
if(path !== null && path !== undefined && path !== '') {
imagePath = path;
} else {
imagePath = 'default.jpg';
}
//Shorthand
let imagePath = getImagePath() || 'default.jpg';
4.分配默认值
我们可以使用OR(||)短路评估为变量指定一个默认值,以防期望值为空。
//Longhand
let imagePath;
let path = getImagePath();
if(path !== null && path !== undefined && path !== '') {
imagePath = path;
} else {
imagePath = 'default.jpg';
}
//Shorthand
let imagePath = getImagePath() || 'default.jpg';
5.AND(&&)短路评估
如需只在变量为真的情况下调用一个函数,则可使用AND(&&)短路评估在一行内完成。
//Longhand
if (isLoggedin) {
goToHomepage();
}
//Shorthand
isLoggedin && goToHomepage();
速记写法这一行,只有在isLoggedin返回结果为真时,goToHomepage()才会执行。
6.交换两个变量
通常交换两个变量需要借助第三个变量。然而通过数组析构赋值,可以轻松交换两个变量。
//Longhand
console.log('You got a missed call from ' + number + ' at ' + time);
//Shorthand
console.log(`You got a missed call from ${number} at ${time}`);
7.箭头函数
//Longhand
function add(num1, num2) {
return num1 + num2;
}
//Shorthand
const add = (num1, num2) => num1 + num2;
8.模板文字
我们通常使用“+”运算符连接字符串值和变量。有了ES6模板,我们可以通过一种更简单的方式实现。
//Longhand
console.log('JavaScript, often abbreviated as JS, is an' + 'programming language thatconforms 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 languagethat conforms to the ECMAScript specification. JavaScript is high-level, oftenjust-in-time compiled, and multi-paradigm.`);
9.多行字符串
对于多行字符串,我们通常使用“+”运算符和换行转义符(n)进行连接。然而可以使用“`”简化代码。
let firstname = 'Amitav';
let lastname = 'Mishra'; //Longhand
let obj = {firstname: firstname, lastname: lastname};
//Shorthand
let obj = {firstname, lastname};
10.多重条件检查
对于多值匹配,可以将所有的值放在数组中,并使用indexOf()或includes()方法。
//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
}
11.对象属性分配
如果变量名和对象键名相同,可以只在对象文字中设置变量名,不用同时设置键和值。JavaScript会自动将键名设置为变量名,并将该值赋为变量值。
let firstname = 'Amitav';
let lastname = 'Mishra'; //Longhand
let obj = {firstname: firstname, lastname: lastname};
//Shorthand
let obj = {firstname, lastname};
12.字符串类型转换为数字类型
有内置的方法,如parseInt 和parseFloat ,可用于将字符串转换为数字。更简单的方法是,在字符串值前加上一元运算符(+)。
//Longhand
let total = parseInt('453');
let average = parseFloat('42.6');
//Shorthand
let total = +'453';
let average = +'42.6';
13.多次重复同一字符串
若要将字符串重复指定的次数,可以使用for 循环。但是使用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次“对不起”进行道歉?试试repeat()方法。如果你想在每次重复时另起一行,只需加上n。
14.指数幂
我们可以用Math.pow()方法求幂。然而用双星号(**)有一个更短的语法。
//Longhand
const power = Math.pow(4, 3); // 64
// Shorthand
const power = 4**3; // 64
15.按位双非运算符
按位双非运算符可以替代Math.floor()方法。
//Longhand
const floor = Math.floor(6.8); // 6
// Shorthand
const floor = ~~6.8; // 6
按位双非运算符方法仅适用于32位整数,即(2**31)-1 = 2147483647。所以对于任何高于2147483647的数字,按位运算符(~~)都会给出错误的结果,所以在这种情况下建议使用Math.floor()。
16.找出数组的最大值和最小值
可以使用for循环遍历数组的每个值,从而找到最大值或最小值。也可以使用Array.reduce()方法来查找数组中的最大值和最小值。
但是使用扩展运算符则可在一行中完成。
// Shorthand
const arr = [2, 8, 15, 4];
Math.max(...arr); // 15
Math.min(...arr); // 2
17.For循环
为遍历数组,通常使用的是传统的for 循环,也可以使用for...of 循环进行遍历。如需访问每个值的索引,可以使用for...in循环。
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]);
}
使用for...in循环还可以遍历对象属性。
let obj = {x: 20, y: 50};
for (const key in obj) {
console.log(obj[key]);
}
18.数组合并
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]
19.多级对象的深度克隆
要深度克隆多级对象,可以遍历每个属性,并检查当前属性是否包含对象。如果是,则通过传递当前属性值(即嵌套对象)对同一函数进行递归调用。也可以使用JSON.stringify()和JSON.parse()在一行中实现。
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));
如果对象属性以函数作为值,则速记技巧(JSON.parse(JSON.stringify(obj)))无效。因为JSON.stringif作用于对象时,以函数作为值的属性会从对象中移除。所以这种情况下,还是要用普通写法。
20.从字符串中获取字符
let str = 'jscurious.com'; //Longhand
str.charAt(2); // c
//Shorthand
str[2]; // c
希望本文能让你有所收获。
![0a37ac1fa5cafa872378802337cca1ce.png](https://i-blog.csdnimg.cn/blog_migrate/1b185b9466d5c4e547ca1d0890178322.png)
留言点赞关注
我们一起分享AI学习与发展的干货
编译组:李紫瑶、骆昱含
相关链接:https://medium.com/javascript-in-plain-english/20-javascript-shorthand-techniques-that-will-save-your-time-f1671aab405f
如转载,请私信小芯,遵守转载规范