10 个超棒的 JavaScript 简写技巧
今天我要分享的是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";
最后,我想借用一段话来作结尾:
代码之所以是我们的敌人,是因为我们中的许多程序员写了很多很多的狗屎代码。如果我们没有办法摆脱,那么最好尽全力保持代码简洁。
如果你喜欢写代码——真的,真的很喜欢写代码——你代码写得越少,说明你的爱意越深。
欢迎关注我的公众号:前端新世界
只关注前端技术,每日分享 JS / CSS 技术教程;Vue、React、jQuery等前端开发组件
10 个超棒的 JavaScript 简写技巧的更多相关文章
- 10个超棒jQuery表单操作代码片段
jQuery绝对是一个伟大的开源javascript类库,是帮助我们快速和高效开发前端应用的利器.可能大家在日常的开发过程中常常会处理表单相关的javascript,在今天这篇代码片段分享文章中,这里 ...
- 不可错过的10个超棒jQuery表单操作代码片段
jQuery 绝对是一个伟大的开源javascript类库,是帮助我们快速和高效开发前端应用的利器.可能大家在日常的开发过程中常常会处理表单相关的 javascript,在今天这篇代码片段分享文章中, ...
- JavaScript简写技巧总结
在日常工作中,JavaScript一些常用的简写技巧,将直接影响到我们的开发效率,现将常用技巧整理如下: 1. 空(null, undefined)验证 当我们创建了一个新的变量,我们通常会去 ...
- JavaScript 简写技巧
1. 声明变量 //普通写法 let x; let y = 20; //简写 let x, y = 20; 2. 给多个变量赋值 //普通写法 let a, b, c; a = 5; b = 8; c ...
- 推荐 10 个超棒的 CSS3 代码生成工具
新的在线工具和 WebApp 帮助开发者快速地创建网站而不用写代码.前端开发已经在框架和代码库方面有了很大的进展. 但是许多开发者已经忘记了代码生成器在构建网站时的价值.下面的资源是完全免费的 Web ...
- 4月超棒的JavaScript游戏开发框架推荐(1) – 51CTO.COM
基于JavaScript开发的游戏是唯一一个能够跨桌面,Web和移动三种平台的.… 查阅全文 ›
- GitHub开源的10个超棒后台管理面板
目录1.AdminLTE 2.vue-Element-Admin 3.tabler 4.Gentelella 5.ng2-admin 6.ant-design-pro 7.blur-admin 8.i ...
- [CSS工具推荐]0001.推荐 10 个超棒的 CSS3 代码生成工具
引言:新的在线工具和 WebApp 帮助开发者快速地创建网站而不用写代码.前端开发已经在框架和代码库方面有了很大的进展. 现在许多开发者已经忘记了代码生成器在构建网站时的价值.下面的资源是完全免费的 ...
- 超棒的javascript移动触摸设备开发类库-QUOjs
开发手机端网站.少不了手势事件? 手势事件怎么写? 手势事件怎么去判断? 对于新手来说.真的很Dan碎! 下面为大家推荐一款插件QUOjs 官方网站http://quojs.tapquo.com/ 这 ...
随机推荐
- UVA 10689 Yet another Number Sequence 矩阵快速幂 水呀水
#include <iostream> #include <cstdio> #include <cstring> #include <algorithm> ...
- leetcode 1122
思路分析: 主要思想:计数排序 先遍历arr1,然后计数,再遍历arr2时同时又排完序了,再继续把arr2不存在的数字,再遍历加到数组后面,也同时排完序了.方便快捷
- 2021/2/5 关于new的一个教训
千万不要在类构造函数的初始化里new任何东西,这会导致析构函数delete一个野指针!构造函数一定要把所有的指针初始化为nullptr! 以下代码会报错(堆内存崩溃): Integer::Intege ...
- HanLP使用教程——NLP初体验
话接上篇NLP的学习坑 自然语言处理(NLP)--简介 ,使用HanLP进行分词标注处词性. HanLP使用简介 HanLP是一系列模型与算法组成的NLP工具包,目标是普及自然语言处理在生产环境中的应 ...
- 高质量代码优化!谈谈重构项目中if-else代码的几点建议
switch if - else只适合在3层之内使用 当条件判断较多时,可以首先考虑使用switch interface 当判断条件还可能动态增加时,可以考虑将switch进一步优化,引入接口inte ...
- [刘阳Java]_MyBatis_注解基本用法_第10讲
MyBatis注解提出,可以说是非常好简化了MyBatis配置文件的使用.下面我们简单地来告诉大家如何使用MyBatis的注解 定义接口 package com.gxa.dao; import jav ...
- 线性回归与梯度下降(ML作业)
Loss函数 题目一:完成computeCost.m function J = computeCost(X, y, theta) %COMPUTECOST Compute cost for linea ...
- 传统二三层转发融合SDN Openflow协议的Hybrid交换机转发流程
Hybrid 交换系统(以下简称Hybrid 交换机)是交换机融合了OVS(Openflow vswitch)原生代码,集传统和Openflow 技术于一体的转发系统.主要解决纯Openflow 基于 ...
- 每天五分钟Go - 变量
变量的声明 1.使用关键词 var 定义,声明后若不赋值,则使用默认值 var 变量名 [变量类型] [=初始值] var a,b,c string var e,f int = 0,1 声明时,如果省 ...
- Gos Log每次查询响应后自动清理临时文件,优化磁盘空间
客户端清理 logc/controllers/file/file.go 压缩后清理原始文件 //压缩成功后 删除原文件 os.Remove(src) 返回后清理压缩文件 defer func() { ...