10 个很棒的 JavaScript 简写
大家好👋
今天我想与大家分享 10 个很棒的JavaScript简写,它们可以帮助您编写更少的代码并完成更多的事情,从而提高您的速度。
开始吧!
1. 合并数组
普通手写:
我们通常使用 Arrayconcat()
方法合并两个数组。该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. 克隆阵列
普通手写:
我们可以使用 Arrayslice()
方法轻松地克隆一个数组,如下所示:
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 }
速记:
哇!为了实现这个逻辑,我们之前写了好多代码。但是有了 Arrayfind()
方法和箭头函数=>
,我们可以轻松地用一行代码实现,如下所示:
// 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. 短路评估
普通手写:
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
就是短路求值到真值表达式。所以,这就好比说,如果第一部分为真,就不用再求值表达式的其余部分了。
最后,我想通过分享Jeff Atwood的一句话来结束这篇文章:
代码之所以是我们的敌人,只是因为我们程序员太多,写了太多代码。如果实在没办法不用代码,那么退而求其次,从简洁开始吧。
如果您热爱编写代码 — — 真的、真正热爱编写代码 — — 您一定会热爱到极致,以至于会尽可能少地编写代码。
如果您喜欢这篇文章,请务必❤它。
您还可以查看我之前的博客:
祝您编码愉快!
社区意见
- @jessycormier
箭头函数
如果不需要this
上下文,则使用箭头函数可以进一步缩短:
let fruits = ['🍉', '🍊', '🍇', '🍎'];
fruits.forEach(console.log);
- @lukeshiru
在数组中查找对象
您可以使用对象解构和箭头函数使其更精简:
// 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";
感谢您的反馈!❤️
文章来源:https://dev.to/palashmon/10-awesome-javascript-shorthands-4pek