总结分享10 个超棒的 JavaScript 简写技巧

 更新时间:2022年06月19日 11:42:12   作者:​ AK_哒哒哒   ​  
这篇文章主要总结分享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 ✨
//=> 🍉
//=> 🍊
//=> 🍇
//=> 🍎

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"

补充几点

箭头函数:

如果你不需要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";

编码习惯

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

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

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

相关文章

  • JavaScript统计数组中相同的数量的方法总结

    JavaScript统计数组中相同的数量的方法总结

    在JavaScript中,我们经常需要对数组中对象的属性进行统计。在本文中,我们将介绍如何使用JavaScript来实现这一功能,文中有详细的代码示例,需要的朋友可以借鉴参考
    2023-05-05
  • js仿支付宝填写支付密码效果实现多方框输入密码

    js仿支付宝填写支付密码效果实现多方框输入密码

    这篇文章主要介绍了js仿支付宝填写支付密码效果实现多方框输入密码的功能,感兴趣的小伙伴们可以参考一下
    2016-03-03
  • BOOTSTRAP时间控件显示在模态框下面的bug修复

    BOOTSTRAP时间控件显示在模态框下面的bug修复

    这篇文章主要介绍了BOOTSTRAP时间控件显示在模态框下面的bug修复,需要的朋友可以参考下
    2015-02-02
  • 使用js实现一个简单的滚动条过程解析

    使用js实现一个简单的滚动条过程解析

    这篇文章主要介绍了使用js实现一个简单的滚动条过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2019-09-09
  • setTimeout在类中使用的问题!

    setTimeout在类中使用的问题!

    setTimeout在类中使用的问题!...
    2007-04-04
  • JS实现不使用图片仿Windows右键菜单效果代码

    JS实现不使用图片仿Windows右键菜单效果代码

    这篇文章主要介绍了JS实现不使用图片仿Windows右键菜单效果代码,涉及文鼎字及css样式的使用技巧,具有一定参考借鉴价值,需要的朋友可以参考下
    2015-10-10
  • Ionic快速安装教程

    Ionic快速安装教程

    Ionic 是目前最有潜力的一款 HTML5 手机应用开发框架。通过 SASS 构建应用程序,它 提供了很多 UI 组件来帮助开发者开发强大的应用。接下来小编给大家介绍如何安装 Ionic 在自己的电脑上搭建一个简单的小应用,感兴趣的朋友一起看看吧
    2016-06-06
  • d3.js实现简单的网络拓扑图实例代码

    d3.js实现简单的网络拓扑图实例代码

    最近一直在学习d3.js,大家都知道d3.js是一个非常不错的数据可视化库,我们可以用它来做一些比较酷的东西,比如可以来显示一些简单的网络拓扑图,这篇文中就通过实例代码给大家介绍了如何利用d3.js实现简单的网络拓扑图,有需要的朋友们可以参考借鉴,下面来一起看看吧。
    2016-11-11
  • JavaScript中apply方法的应用技巧小结

    JavaScript中apply方法的应用技巧小结

    这篇文章给大家总结了在js中apply方法的一些应用技巧,通过这些技巧对大家日常的使用相信会有帮助,有需要的朋友们下面来一起看看吧。
    2016-09-09
  • 微信小程序实战之自定义抽屉菜单(7)

    微信小程序实战之自定义抽屉菜单(7)

    这篇文章主要为大家详细介绍了微信小程序实战之自定义抽屉菜单效果,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2017-04-04

最新评论