网站首页 > 基础教程 正文
今天我要分享的是10个超棒的JavaScript简写方法,可以加快开发速度,让你的开发工作事半功倍哦。
Freemen App是一款专注于IT程序员求职招聘的一个求职平台,旨在帮助IT技术工作者能更好更快入职及努力协调IT技术者工作和生活的关系,让工作更自由!
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 = ['', '', ''];
// 讲 apples 数组中的所有元素添加到 fruits 数组的起始位置
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}
];
// 在数组中找到 name 为 `Apples` 的对象
function getApples(arr, value) {
for (let index = 0; index < arr.length; index++) {
if (arr[index].name === 'Apples') { //=>
return arr[index];
}
}
}
let result = getApples(inventory);
console.log( result )
//=> { name: "Apples", quantity: 10 }
简写方法:
哇!上面我们写了这么多代码来实现这个逻辑。但是使用Array中的find()方法和箭头函数=>,允许我们像这样一行搞定:
// 在数组中找到 name 为 `Apples` 的对象
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);
在数组中查找对象
你可以使用对象解构和箭头函数使代码更精简:
// 在数组中找到 name 为 `Apples` 的对象
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";
最后,我想借用一段话来作结尾:
代码之所以是我们的敌人,是因为我们中的许多程序员写了很多很多的狗屎代码。如果我们没有办法摆脱,那么最好尽全力保持代码简洁。
如果你喜欢写代码——真的,真的很喜欢写代码——你代码写得越少,说明你的爱意越深。
希望本文对你有所帮助。如有错误,还请大家指正。感谢阅读!
猜你喜欢
- 2024-12-22 Vue进阶(十三):MOCK vue mock.js教程
- 2024-12-22 js常用数组API方法汇总 js数组的用法
- 2024-12-22 js中常见的几种排序算法 js常用排序
- 2024-12-22 一文掌握:掌握 JavaScript 中的内存生命周期。
- 2024-12-22 前端笔记-js浅拷贝和深拷贝 js实现浅拷贝和深拷贝
- 2024-12-22 js中的数组拷贝(浅拷贝,深拷贝) js深拷贝一个数组
- 05-24php实现三方支付的方法有哪些?
- 05-24CosmicSting 漏洞影响 75% 的 Adobe Commerce 和 Magento 网站
- 05-24Java接口默认方法的奇妙用途
- 05-24抽象类和接口
- 05-24详解Java抽象类和接口
- 05-24拒绝接口裸奔!开放API接口签名验证
- 05-24每天学Java!Java中的接口有什么作用
- 05-24Java:在Java中使用私有接口方法
- 最近发表
- 标签列表
-
- jsp (69)
- gitpush (78)
- gitreset (66)
- python字典 (67)
- dockercp (63)
- gitclone命令 (63)
- dockersave (62)
- linux命令大全 (65)
- pythonif (86)
- location.href (69)
- dockerexec (65)
- tail-f (79)
- deletesql (62)
- c++模板 (62)
- linuxgzip (68)
- 字符串连接 (73)
- nginx配置文件详解 (61)
- html标签 (69)
- c++初始化列表 (64)
- mysqlinnodbmyisam区别 (63)
- arraylistadd (66)
- console.table (62)
- mysqldatesub函数 (63)
- window10java环境变量设置 (66)
- c++虚函数和纯虚函数的区别 (66)