经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » JS/JS库/框架 » JavaScript » 查看文章
总结分享10 个超棒的 JavaScript 简写技巧
来源:jb51  时间:2022/6/20 8:40:42  对本文有异议

1.合并数组

普通写法:

我们通常使用Array中的concat()方法合并两个数组。用concat()方法来合并两个或多个数组,不会更改现有的数组,而是返回一个新的数组。请

看一个简单的例子:

  1. let apples = ['??', '??'];
  2. let fruits = ['??', '??', '??'].concat(apples);
  3. console.log( fruits );
  4. //=> ["??", "??", "??", "??", "??"]

简写写法:

我们可以通过使用ES6扩展运算符(...)来减少代码,如下所示:

  1. let apples = ['??', '??'];
  2. let fruits = ['??', '??', '??', ...apples]; // <-- here
  3. console.log( fruits );
  4. //=> ["??", "??", "??", "??", "??"]

2.合并数组(在开头位置)

普通写法: 假设我们想将apples数组中的所有项添加到Fruits数组的开头,而不是像上一个示例中那样放在末尾。我们可以使用Array.prototype.unshift()来做到这一点:

  1. let apples = ['??', '??'];
  2. let fruits = ['??', '??', '??'];
  3. // Add all items from apples onto fruits at start
  4. Array.prototype.unshift.apply(fruits, apples)
  5. console.log( fruits );
  6. //=> ["??", "??", "??", "??", "??"]

简写写法:

我们依然可以使用ES6扩展运算符(...)缩短这段长代码,如下所示:

  1. let apples = ['??', '??'];
  2. let fruits = [...apples, '??', '??', '??']; // <-- here
  3. console.log( fruits );
  4. //=> ["??", "??", "??", "??", "??"]

3.克隆数组

普通写法:

我们可以使用Array中的slice()方法轻松克隆数组,如下所示:

  1. let fruits = ['??', '??', '??', '??'];
  2. let cloneFruits = fruits.slice();
  3. console.log( cloneFruits );
  4. //=> ["??", "??", "??", "??"]

简写写法:

我们可以使用ES6扩展运算符(...)像这样克隆一个数组:

  1. let fruits = ['??', '??', '??', '??'];
  2. let cloneFruits = [...fruits]; // <-- here
  3. console.log( cloneFruits );
  4. //=> ["??", "??", "??", "??"]

4.解构赋值

普通写法:

在处理数组时,我们有时需要将数组“解包”成一堆变量,如下所示:

  1. let apples = ['??', '??'];
  2. let redApple = apples[0];
  3. let greenApple = apples[1];
  4. console.log( redApple ); //=> ??
  5. console.log( greenApple ); //=> ??

简写写法:

我们可以通过解构赋值用一行代码实现相同的结果:

  1. let apples = ['??', '??'];
  2. let [redApple, greenApple] = apples; // <-- here
  3. console.log( redApple ); //=> ??
  4. console.log( greenApple ); //=> ??

5.模板字面量

普通写法:

通常,当我们必须向字符串添加表达式时,我们会这样做:

  1. // Display name in between two strings
  2. let name = 'Palash';
  3. console.log('Hello, ' + name + '!');
  4. //=> Hello, Palash!
  5. // Add & Subtract two numbers
  6. let num1 = 20;
  7. let num2 = 10;
  8. console.log('Sum = ' + (num1 + num2) + ' and Subtract = ' + (num1 - num2));
  9. //=> Sum = 30 and Subtract = 10

简写写法:

通过模板字面量,我们可以使用反引号(``),这样我们就可以将表达式包装在${…}`中,然后嵌入到字符串,如下所示:

  1. // Display name in between two strings
  2. let name = 'Palash';
  3. console.log(`Hello, ${name}!`); // <-- No need to use + var + anymore
  4. //=> Hello, Palash!
  5. // Add two numbers
  6. let num1 = 20;
  7. let num2 = 10;
  8. console.log(`Sum = ${num1 + num2} and Subtract = ${num1 - num2}`);
  9. //=> Sum = 30 and Subtract = 10

6.For循环

普通写法:

我们可以使用for循环像这样循环遍历一个数组:

  1. let fruits = ['??', '??', '??', '??'];
  2. // Loop through each fruit
  3. for (let index = 0; index < fruits.length; index++) {
  4. console.log( fruits[index] ); // <-- get the fruit at current index
  5. }
  6. //=> ??
  7. //=> ??
  8. //=> ??
  9. //=> ??

简写写法:

我们可以使用for...of语句实现相同的结果,而代码要少得多,如下所示:

  1. let fruits = ['??', '??', '??', '??'];
  2. // Using for...of statement
  3. for (let fruit of fruits) {
  4. console.log( fruit );
  5. }
  6. //=> ??
  7. //=> ??
  8. //=> ??
  9. //=> ??

7.箭头函数

普通写法:

要遍历数组,我们还可以使用Array中的forEach()方法。但是需要写很多代码,虽然比最常见的for循环要少,但仍然比for...of语句多一点:

  1. let fruits = ['??', '??', '??', '??'];
  2. // Using forEach method
  3. fruits.forEach(function(fruit){
  4. console.log( fruit );
  5. });
  6. //=> ??
  7. //=> ??
  8. //=> ??
  9. //=> ??

简写写法:

但是使用箭头函数表达式,允许我们用一行编写完整的循环代码,如下所示:

  1. let fruits = ['??', '??', '??', '??'];
  2. fruits.forEach(fruit => console.log( fruit )); // <-- Magic ?
  3. //=> ??
  4. //=> ??
  5. //=> ??
  6. //=> ??

8.在数组中查找对象

普通写法:

要通过其中一个属性从对象数组中查找对象的话,我们通常使用for循环:

  1. let inventory = [
  2. {name: 'Bananas', quantity: 5},
  3. {name: 'Apples', quantity: 10},
  4. {name: 'Grapes', quantity: 2}
  5. ];
  6. // Get the object with the name `Apples` inside the array
  7. function getApples(arr, value) {
  8. for (let index = 0; index < arr.length; index++) {
  9. // Check the value of this object property `name` is same as 'Apples'
  10. if (arr[index].name === 'Apples') { //=> ??
  11.  
  12. // A match was found, return this object
  13. return arr[index];
  14. }
  15. }
  16. }
  17. let result = getApples(inventory);
  18. console.log( result )
  19. //=> { name: "Apples", quantity: 10 }

简写写法:

上面我们写了这么多代码来实现这个逻辑。但是使用Array中的find()方法和箭头函数=>,允许我们像这样一行搞定:

  1. // Get the object with the name `Apples` inside the array
  2. function getApples(arr, value) {
  3. return arr.find(obj => obj.name === 'Apples'); // <-- here
  4. }
  5. let result = getApples(inventory);
  6. console.log( result )
  7. //=> { name: "Apples", quantity: 10 }

9.将字符串转换为整数

普通写法:

parseInt()函数用于解析字符串并返回整数:

  1. let num = parseInt("10")
  2. console.log( num ) //=> 10
  3. console.log( typeof num ) //=> "number"

简写写法:

我们可以通过在字符串前添加+前缀来实现相同的结果,如下所示:

  1. let num = +"10";
  2. console.log( num ) //=> 10
  3. console.log( typeof num ) //=> "number"
  4. console.log( +"10" === 10 ) //=> true

10.短路求值

普通写法:

如果我们必须根据另一个值来设置一个值不是falsy值,一般会使用if-else语句,就像这样:

  1. function getUserRole(role) {
  2. let userRole;
  3. // If role is not falsy value
  4. // set `userRole` as passed `role` value
  5. if (role) {
  6. userRole = role;
  7. } else {
  8. // else set the `userRole` as USER
  9. userRole = 'USER';
  10. }
  11. return userRole;
  12. }
  13. console.log( getUserRole() ) //=> "USER"
  14. console.log( getUserRole('ADMIN') ) //=> "ADMIN"

简写写法:

但是使用短路求值(||),我们可以用一行代码执行此操作,如下所示:

  1. function getUserRole(role) {
  2. return role || 'USER'; // <-- here
  3. }
  4. console.log( getUserRole() ) //=> "USER"
  5. console.log( getUserRole('ADMIN') ) //=> "ADMIN"

补充几点

箭头函数:

如果你不需要this上下文,则在使用箭头函数时代码还可以更短:

  1. let fruits = ['??', '??', '??', '??'];
  2. fruits.forEach(console.log);

在数组中查找对象:

你可以使用对象解构和箭头函数使代码更精简:

  1. // Get the object with the name `Apples` inside the array
  2. const getApples = array => array.find(({ name }) => name === "Apples");
  3. let result = getApples(inventory);
  4. console.log(result);
  5. //=> { name: "Apples", quantity: 10 }

短路求值替代方案:

  1. const getUserRole1 = (role = "USER") => role;
  2. const getUserRole2 = role => role ?? "USER";
  3. const getUserRole3 = role => role ? role : "USER";

编码习惯

最后我想说下编码习惯。代码规范比比皆是,但是很少有人严格遵守。究其原因,多是在代码规范制定之前,已经有自己的一套代码习惯,很难短时间改变自己的习惯。良好的编码习惯可以为后续的成长打好基础。下面,列举一下开发规范的几点好处,让大家明白代码规范的重要性:

  • 规范的代码可以促进团队合作。
  • 规范的代码可以减少 Bug 处理。
  • 规范的代码可以降低维护成本。
  • 规范的代码有助于代码审查。
  • 养成代码规范的习惯,有助于程序员自身的成长。

到此这篇关于总结分享10 个超棒的 JavaScript 简写技巧的文章就介绍到这了,更多相关JS简写技巧内容请搜索w3xue以前的文章或继续浏览下面的相关文章希望大家以后多多支持w3xue!

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号