10个超棒的Js简写技巧

更新日期: 2022-04-27阅读: 633标签: 技巧

今天我要分享的是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";

最后,我想借用一段话来作结尾:

代码之所以是我们的敌人,是因为我们中的许多程序员写了很多很多的狗屎代码。如果我们没有办法摆脱,那么最好尽全力保持代码简洁。
如果你喜欢写代码——真的,真的很喜欢写代码——你代码写得越少,说明你的爱意越深。


链接: https://www.fly63.com/article/detial/11397

微信小程序技巧_你需要知道的小程序开发技巧

一直以来进行了比较多的微信小程序开发... 总会接触到一些和官方组件或 api 相关或其无法解决的需求,于是决定在这里小小的整理一下微信小程序开发的一些技巧

微信小程序分享到朋友圈方法与技巧

小程序提供onShareAppMessage 函数,此函数只支持分享给我微信朋友,小程序如何分享到朋友圈呢?使用canvas绘制一张图片,并用wx.previewImage预览图片,然后长按图片保存图片到手机。

前端新手程序员不知道的 20个小技巧

前端新手程序员不知道的 20个小技巧:作为前端开发者,使用双显示器能大幅提高开发效率、学编程最好的语言不是PHP,是English、东西交付之前偷偷测试一遍、问别人之前最好先自己百度,google一下、把觉得不靠谱的需求放到最后做,很可能到时候需求就变了...

小技巧:检查你本地及公共 IP 地址

本地的 IP 地址是分配给你计算机上的内部硬件或虚拟网卡的本地/私有 IP 地址。根据你的 LAN 配置,上述 IP 地址可能是静态或动态的。公共的 IP 地址是你的 Internet 服务提供商(ISP)为你分配的公共/外部 IP 地址。

12 个 CSS 高级技巧汇总

使用 :not() 在菜单上应用/取消应用边框;给body添加行高;所有一切都垂直居中;逗号分隔的列表;使用负的 nth-child 选择项目;对图标使用SVG;优化显示文本;对纯CSS滑块使用 max-height;继承 box-sizing

26 个 jQuery使用技巧

禁用右键点击;禁用搜索文本框;新窗口打开链接;检测浏览器;预加载图片;样式筛选;列高度相同;字体大小调整;返回页面顶部;获取鼠标的xy坐标;验证元素是否为空;替换元素

提高网站加载速度的一些小技巧

为你网站的用户留下良好的第一印象是非常必要的。随着商业领域的竞争,拥有一个吸引人的网站可以帮助你脱颖而出。研究表明,如果加载时间超过3秒,会有 40% 的用户放弃访问你的网站

《CSS世界》中提到的实用技巧

清除浮动主要用于子元素浮动(float)之后,父元素无法撑起高度和宽度。文字少时居中,多时靠左因为div嵌套着p,所以p的尺寸并不会超过div。但是要注意,当p的内容为英文单词组成的时候

不常被提及的JavaScript小技巧

这次我们主要来分享11个在日常教程中不常被提及的JavaScript小技巧,他们往往在我们的日常工作中经常出现,但是我们又很容易忽略。Set类型是在ES6中新增的,它类似于数组,但是成员的值都是唯一的

CSS-in-JS 库 styled-class

为什么要在JavaScript里写CSS?避免命名全局污染,条件和动态样式(比如选择主题色之类的),在框架层面进行限制或补充(比如补全供应商前缀),避免业务人员使用奇技淫巧

点击更多...

内容以共享、参考、研究为目的,不存在任何商业目的。其版权属原作者所有,如有侵权或违规,请与小编联系!情况属实本人将予以删除!