明天我要分享的是10个超棒的JavaScript简写办法,能够放慢开发速度,让你的开发工作事倍功半哦。
开始吧!
1. 合并数组
一般写法:
咱们通常应用Array
中的concat()
办法合并两个数组。用concat()
办法来合并两个或多个数组,不会更改现有的数组,而是返回一个新的数组。请看一个简略的例子:
let apples = ['🍎', '🍏'];
let fruits = ['🍉', '🍊', '🍇'].concat(apples);
console.log( fruits );
//=> ["🍉", "🍊", "🍇", "🍎", "🍏"]
简写办法:
咱们能够通过应用ES6扩大运算符(...
)来缩小代码,如下所示:
let apples = ['🍎', '🍏'];
let fruits = ['🍉', '🍊', '🍇', ...apples]; // <-- here
console.log( fruits );
//=> ["🍉", "🍊", "🍇", "🍎", "🍏"]
失去的输入与一般写法雷同。
2. 合并数组(在结尾地位)
一般写法:
假如咱们想将apples
数组中的所有项增加到Fruits
数组的结尾,而不是像上一个示例中那样放在开端。咱们能够应用Array.prototype.unshift()
来做到这一点:
let apples = ['🍎', '🍏'];
let fruits = ['🥭', '🍌', '🍒'];
// Add all items from apples onto fruits at start
Array.prototype.unshift.apply(fruits, apples)
console.log( fruits );
//=> ["🍎", "🍏", "🥭", "🍌", "🍒"]
当初红苹果和绿苹果会在结尾地位合并而不是开端。
简写办法:
咱们仍然能够应用ES6扩大运算符(...
)缩短这段长代码,如下所示:
let apples = ['🍎', '🍏'];
let fruits = [...apples, '🥭', '🍌', '🍒']; // <-- here
console.log( fruits );
//=> ["🍎", "🍏", "🥭", "🍌", "🍒"]
3. 克隆数组
一般写法:
咱们能够应用Array
中的slice()
办法轻松克隆数组,如下所示:
let fruits = ['🍉', '🍊', '🍇', '🍎'];
let cloneFruits = fruits.slice();
console.log( cloneFruits );
//=> ["🍉", "🍊", "🍇", "🍎"]
简写办法:
咱们能够应用ES6扩大运算符(...
)像这样克隆一个数组:
let fruits = ['🍉', '🍊', '🍇', '🍎'];
let cloneFruits = [...fruits]; // <-- here
console.log( cloneFruits );
//=> ["🍉", "🍊", "🍇", "🍎"]
4. 解构赋值
一般写法:
在解决数组时,咱们有时须要将数组“解包”成一堆变量,如下所示:
let apples = ['🍎', '🍏'];
let redApple = apples[0];
let greenApple = apples[1];
console.log( redApple ); //=> 🍎
console.log( greenApple ); //=> 🍏
简写办法:
咱们能够通过解构赋值用一行代码实现雷同的后果:
let apples = ['🍎', '🍏'];
let [redApple, greenApple] = apples; // <-- here
console.log( redApple ); //=> 🍎
console.log( greenApple ); //=> 🍏
5. 模板字面量
一般写法:
通常,当咱们必须向字符串增加表达式时,咱们会这样做:
// Display name in between two strings
let name = 'Palash';
console.log('Hello, ' + name + '!');
//=> Hello, Palash!
// Add & Subtract two numbers
let num1 = 20;
let num2 = 10;
console.log('Sum = ' + (num1 + num2) + ' and Subtract = ' + (num1 - num2));
//=> Sum = 30 and Subtract = 10
简写办法:
通过模板字面量,咱们能够应用反引号(),这样咱们就能够将表达式包装在
${…}\`中,而后嵌入到字符串,如下所示:
// Display name in between two strings
let name = 'Palash';
console.log(`Hello, ${name}!`); // <-- No need to use + var + anymore
//=> Hello, Palash!
// Add two numbers
let num1 = 20;
let num2 = 10;
console.log(`Sum = ${num1 + num2} and Subtract = ${num1 - num2}`);
//=> Sum = 30 and Subtract = 10
6. For循环
一般写法:
咱们能够应用for
循环像这样循环遍历一个数组:
let fruits = ['🍉', '🍊', '🍇', '🍎'];
// Loop through each fruit
for (let index = 0; index < fruits.length; index++) {
console.log( fruits[index] ); // <-- get the fruit at current index
}
//=> 🍉
//=> 🍊
//=> 🍇
//=> 🍎
简写办法:
咱们能够应用for...of
语句实现雷同的后果,而代码要少得多,如下所示:
let fruits = ['🍉', '🍊', '🍇', '🍎'];
// Using for...of statement
for (let fruit of fruits) {
console.log( fruit );
}
//=> 🍉
//=> 🍊
//=> 🍇
//=> 🍎
7. 箭头函数
一般写法:
要遍历数组,咱们还能够应用Array
中的forEach()
办法。然而须要写很多代码,尽管比最常见的for
循环要少,但依然比for...of
语句多一点:
let fruits = ['🍉', '🍊', '🍇', '🍎'];
// Using forEach method
fruits.forEach(function(fruit){
console.log( fruit );
});
//=> 🍉
//=> 🍊
//=> 🍇
//=> 🍎
简写办法:
然而应用箭头函数表达式,容许咱们用一行编写残缺的循环代码,如下所示:
let fruits = ['🍉', '🍊', '🍇', '🍎'];
fruits.forEach(fruit => console.log( fruit )); // <-- Magic ✨
//=> 🍉
//=> 🍊
//=> 🍇
//=> 🍎
大多数时候我应用的是带箭头函数的forEach
循环,这里我把for...of
语句和forEach
循环都展现进去,不便大家依据本人的爱好应用代码。
8. 在数组中查找对象
一般写法:
要通过其中一个属性从对象数组中查找对象的话,咱们通常应用for
循环:
let inventory = [
{name: 'Bananas', quantity: 5},
{name: 'Apples', quantity: 10},
{name: 'Grapes', quantity: 2}
];
// Get the object with the name `Apples` inside the array
function getApples(arr, value) {
for (let index = 0; index < arr.length; index++) {
// Check the value of this object property `name` is same as 'Apples'
if (arr[index].name === 'Apples') { //=> 🍎
// A match was found, return this object
return arr[index];
}
}
}
let result = getApples(inventory);
console.log( result )
//=> { name: "Apples", quantity: 10 }
简写办法:
哇!下面咱们写了这么多代码来实现这个逻辑。然而应用Array
中的find()
办法和箭头函数=>
,容许咱们像这样一行搞定:
// Get the object with the name `Apples` inside the array
function getApples(arr, value) {
return arr.find(obj => obj.name === 'Apples'); // <-- here
}
let result = getApples(inventory);
console.log( result )
//=> { name: "Apples", quantity: 10 }
9. 将字符串转换为整数
一般写法:
parseInt()
函数用于解析字符串并返回整数:
let num = parseInt("10")
console.log( num ) //=> 10
console.log( typeof num ) //=> "number"
简写办法:
咱们能够通过在字符串前增加+
前缀来实现雷同的后果,如下所示:
let num = +"10";
console.log( num ) //=> 10
console.log( typeof num ) //=> "number"
console.log( +"10" === 10 ) //=> true
10. 短路求值
一般写法:
如果咱们必须依据另一个值来设置一个值不是falsy值,个别会应用if-else
语句,就像这样:
function getUserRole(role) {
let userRole;
// If role is not falsy value
// set `userRole` as passed `role` value
if (role) {
userRole = role;
} else {
// else set the `userRole` as USER
userRole = 'USER';
}
return userRole;
}
console.log( getUserRole() ) //=> "USER"
console.log( getUserRole('ADMIN') ) //=> "ADMIN"
简写办法:
然而应用短路求值(||
),咱们能够用一行代码执行此操作,如下所示:
function getUserRole(role) {
return role || 'USER'; // <-- here
}
console.log( getUserRole() ) //=> "USER"
console.log( getUserRole('ADMIN') ) //=> "ADMIN"
基本上,expression1 || expression2
被评估为真
表达式。因而,这就意味着如果第一部分为真,则不用费神求值表达式的其余部分。
补充几点
箭头函数
如果你不须要this
上下文,则在应用箭头函数时代码还能够更短:
let fruits = ['🍉', '🍊', '🍇', '🍎'];
fruits.forEach(console.log);
在数组中查找对象
你能够应用对象解构和箭头函数使代码更精简:
// Get the object with the name `Apples` inside the array
const getApples = array => array.find(({ name }) => name === "Apples");
let result = getApples(inventory);
console.log(result);
//=> { name: "Apples", quantity: 10 }
短路求值代替计划
const getUserRole1 = (role = "USER") => role;
const getUserRole2 = role => role ?? "USER";
const getUserRole3 = role => role ? role : "USER";
编码习惯
最初我想说下编码习惯。代码标准亘古未有,然而很少有人严格遵守。究其原因,多是在代码标准制订之前,曾经有本人的一套代码习惯,很难短时间扭转本人的习惯。良好的编码习惯能够为后续的成长打好根底。上面,列举一下开发标准的几点益处,让大家明确代码标准的重要性:
- 标准的代码能够促成团队单干。
- 标准的代码能够缩小 Bug 解决。
- 标准的代码能够升高保护老本。
- 标准的代码有助于代码审查。
- 养成代码标准的习惯,有助于程序员本身的成长。
我本人在看的是《阿里前端开发标准》,外面的代码标准很全,并且根本通用,看完很受用。篇幅起因,上面以截图展现目录及局部内容,残缺PDF点击这里即可收费下载获取。
目录
一、编码标准
二、Vue我的项目标准
以上即是《阿里前端开发标准》,须要的小伙伴点击这里即可收费下载获取。
最初,我想借用一段话来作结尾:
代码之所以是咱们的敌人,是因为咱们中的许多程序员写了很多很多的狗屎代码。如果咱们没有方法解脱,那么最好尽全力放弃代码简洁。
如果你喜爱写代码——真的,真的很喜爱写代码——你代码写得越少,阐明你的爱意越深。
发表回复