JavaScript 简写编码技巧
在这篇博文中,我整理了一些实用的 JavaScript 简写编码技巧。JavaScript 简写是一种很好的编码技巧,可以帮助程序员优化和简化他们的 JavaScript 代码。
1. 如果存在
在代码中的某个位置,我们需要检查某个变量是否存在。if present 简写可以帮助您用简单的代码实现这一点。
// Longhand
if(isGirl === true){
console.log('isGirl')
}
//Shorthand
if(isGirl){
console.log('isGirl')
}
注意:只要isGirl
是真值,上面例子中的简写就会被评估。
2. 三元运算符
我们可以在一行代码中使用条件(三元)运算符代替语句。if ... else
//Longhand
const age = 19;
let status;
if(age > 18){
status = "An adult"
}else{
status = "Young"
}
//Shorthand
const status = age > 18 ? "An Adult" : "Young"
3.箭头函数
传统的 javascript 函数可以用 ES6 箭头函数来简化。
//Longhand
function greet(name){
console.log('Welcome ', name)
}
//Shorthand
great = name => console.log(name)
4. 解构赋值
解构赋值不仅可以节省大量时间,还可以使你的代码更干净、更简单。
const vehicles = {
car: "🚗",
taxi: "🚕",
bus: "🚌",
minibus: "🚐"
};
// Longhand
let car = vehicles.car
let taxi = vehicles.taxi
let bus = vehicles.bus
let minibus = vehicles.minibus
// Shorthand
const { car, taxi, bus, minibus } = vehicles
5. For循环
下面的示例使用了for ... of
简化for ... in
的代码。
const animals = ["goat", "sheep", "dog", "cat"]
// Longhand
for (let i=0; i < animals.length; i++){
console.log(animals[i])
}
// Shorthand
for(let animal of animals){
console.log(animal)
}
// Getting the index
for(let index in animals){
console.log(animals[index])
}
6. 模板字符串
连接多个字符串变量很常见'+'
。ES6 模板字面量使用反引号和 使连接更加容易${}
。
// Longhand
const checkOut = 'Order price: ' + price + ' at a discount of ' + discount
// Shorthand
const checkOut = `Order price: ${price} at a discount of ${discount}`
7. 多行字符串
使用反引号可以使在代码中编写字符串行变得更加容易。
// Longhand
const msg = 'A wonderful serenity has taken possession\n\t'
+ 'of my entire soul, like these sweet mornings of spring\n\t'
+'which I enjoy with my whole heart. I am alone,\n\t'
+'and feel the charm of existence in this spot,\n\t'
+'which was created for the bliss of souls like mine.\n\t '
//Shorthand
const msg = `A wonderful serenity has taken possession
of my entire soul, like these sweet mornings of spring
which I enjoy with my whole heart. I am alone,
and feel the charm of existence in this spot,
which was created for the bliss of souls like mine.`
8.指数幂
// Longhand
Math.pow(5,3) // 125
// Shorthand
5**3 // 125
9.声明变量
当声明多个变量时,简写可以节省大量时间。
// Longhand
let a;
let b = 6;
let c;
// Shorthand
let a, b = 6, c;
10.默认参数值
ES6 可以在函数声明中为变量分配默认值。
//Longhand
function checkOut(quantity, price, discount){
if(discount === undefined){
discount = 0
}
return quantity * price + discount
}
// Shorthand
checkOut = (quantity, price, discount = 0) => (quantity * price - discount)
11. 数组查找
//Longhand
const animals = [
{name: 'octopus', animalClass: 'invertebrates'},
{name: 'shark', animalClass: 'fish'},
{name: 'toad', animalClass: 'amphibians'},
{name: 'snake', animalClass: 'reptiles'},
{name: 'ostrich', animalClass: 'birds'},
{name: 'cat', animalClass: 'mammals'},
]
function findReptile(name){
for(let i=0; i < animals.length; ++i){
if(animals[i].animalClass === 'reptiles' && animals[i].name === name){
return animals[i]
}
}
}
// Shorthand
findReptile = name => (
animals.find(animal => animal.animalClass ==='reptiles' && animal.name === name)
)
12. 短路评估
使用短路逻辑运算符有助于将代码行数减少为一行。
// Longhand
let person;
if(job){
person = job
}else{
person = 'unemployed'
}
// Shorthand
const person = job || 'unemployed'
13. 将字符串转换为数字
parseInt
无需使用或即可轻松将字符串转换为数字parseFloat
。
// Longhand
const quantity = parseInt("250")
const price = parseFloat("432.50")
// Shorthand
const quantity = +"250" // converts to int
const price = +"432.50" // converts to float
14. 扩展运算符
我见过很多开发者使用[].concat()
连接两个数组并array.slice()
克隆一个数组的方法。但这可以通过 JavaScript ES6 的扩展运算符轻松实现。
const birds = ["parrot", "swan", "eagle", "duck"]
// Longhand
// joining arrays
const animals = ["zebra", "giraffe", "llama", "raccoon"].concat(birds)
// cloning arrays
const newBirds = birds.slice()
// Shorthand
// joining arrays
const animals = ["zebra", "giraffe", "llama", "raccoon", ...birds]
//cloning arrays
const newBirds = [...birds]
15. Null、Undefined、Empty 检查
当变量未定义、为空或为空时,执行操作可以用简写简单完成。
// Longhand
if(variable !== undefined || variable !== "" || variable !== null){
console.log(variable)
}
// Shorthand
if(varible){
console.log(variable)
}
// assigning variable to newVariable when variable is truthy
let newVariable = variable || ""
16. 十进制底数指数
输入 1e4 比输入 10000 更容易、更简洁。
// Longhand
for(let i; i < 1000000; i++){}
// Shorthand
for(let i; i < 1e6; i++){}
// evaluates to true
1e0 === 1;
1e1 === 10;
1e2 === 100;
1e3 === 1000;
1e4 === 10000;
1e5 === 100000;
17. 对象属性
在 ES6 中,我们可以轻松地为对象分配属性。如果变量名与对象键相同,则可以利用简写符号。
const quantity = 324, price = 45.50;
// Longhand
const product = {quantity: quantity, price: price}
// Shorthand
const product = {quantity, price}
18.隐式回报
使用箭头函数,您可以在一行代码中返回隐式结果。
// Longhand
function area(radius){
return Math.PI * radius**2
}
//Shorthand
area = radius => Math.PI * radius**2
// return multi-line statement
area = radius => (
Math.PI * radius**2
)
以上是我在这篇文章中收集的一些速记。如果还想找到更多,请在评论区分享你觉得有用的速记。
文章来源:https://dev.to/ayekpleclemence/javascript-shorthand-coding-techniques-43pd