34个JavaScript简写优化技术

更新日期: 2021-04-13阅读: 1.4k标签: 优化

开发者的生活总是在学习新的东西,跟上变化不应该比现在更难,我的动机是介绍所有 JavaScript 的最佳实践,比如简写功能,作为一个前端开发者,我们必须知道,让我们的生活在 2021 年变得更轻松。

你可能做了很长时间的 JavaScript 开发,但有时你可能没有更新最新的特性,这些特性可以解决你的问题,而不需要做或编写一些额外的代码。这些技术可以帮助您编写干净和优化的 JavaScript 代码。此外,这些主题可以帮助你为 2021 年的 JavaScript 面试做准备。

1.如果有多个条件

我们可以在数组中存储多个值,并且可以使用数组 include 方法。

  1. //Longhand
  2. if (
  3.   x === "abc" ||
  4.   x === "def" ||
  5.   x === "ghi" ||
  6.   x === "jkl"
  7. ) {
  8.   //logic
  9. }
  10. //Shorthand
  11. if (["abc", "def", "ghi", "jkl"].includes(x)) {
  12.   //logic
  13. }

2.如果为真…否则简写

这对于我们有 if-else 条件,里面不包含更大的逻辑时,是一个较大的捷径。我们可以简单的使用三元运算符来实现这个简写。

  1. // Longhand
  2. let test: boolean;
  3. if (x > 100) {
  4.   test = true;
  5. } else {
  6.   test = false;
  7. }
  8. // Shorthand
  9. let test = x > 10 ? true : false;
  10. //or we can use directly
  11. let test = x > 10;
  12. console.log(test);

当我们有嵌套条件时,我们可以采用这种方式。

  1. let x = 300,
  2.   test2 =
  3.     x > 100
  4.       ? "greater 100"
  5.       : x < 50
  6.       ? "less 50"
  7.       : "between 50 and 100";
  8. console.log(test2); // "greater than 100"

3.声明变量

当我们要声明两个具有共同值或共同类型的变量时,可以使用此简写形式。

  1. //Longhand
  2. let test1;
  3. let test2 = 1;
  4. //Shorthand
  5. let test1,
  6.   test2 = 1;

4.Null, Undefined,空检查

当我们创建新的变量时,有时我们想检查我们引用的变量的值是否为空或 undefined。JavaScript 确实有一个非常好的简写工具来实现这些功能。

  1. // Longhand
  2. if (test1 !== null || test1 !== undefined || test1 !== "") {
  3.   let test2 = test1;
  4. }
  5. // Shorthand
  6. let test2 = test1 || "";

5.null 值检查和分配默认值

  1. let test1 = null,
  2.   test2 = test1 || "";
  3. console.log("null check", test2); // output will be ""
  4. 6.undefined 值检查和分配默认值
  5. js
  6. let test1 = undefined,
  7.   test2 = test1 || "";
  8. console.log("undefined check", test2); // output will be ""

正常值检查

  1. let test1 = "test",
  2.   test2 = test1 || "";
  3. console.log(test2); // output: 'test'

7.将值分配给多个变量

当我们处理多个变量并希望将不同的值分配给不同的变量时,此简写技术非常有用。

  1. //Longhand
  2. let test1, test2, test3;
  3. test1 = 1;
  4. test2 = 2;
  5. test3 = 3;
  6. //Shorthand
  7. let [test1, test2, test3] = [1, 2, 3];

8.赋值运算符简写

我们在编程中处理很多算术运算符,这是将运算符分配给 JavaScript 变量的有用技术之一。

  1. // Longhand
  2. test1 = test1 + 1;
  3. test2 = test2 - 1;
  4. test3 = test3 * 20;
  5. // Shorthand
  6. test1++;
  7. test2--;
  8. test3 *= 20;

9.如果存在简写

这是我们大家都在使用的常用简写之一,但仍然值得一提。

  1. // Longhand
  2. if (test1 === true) or if (test1 !== "") or if (test1 !== null)
  3. // Shorthand //it will check empty string,null and undefined too
  4. if (test1)

注意:如果 test1 有任何值,它将在 if 循环后进入逻辑,该运算符主要用于 null 或 undefined 的检查。

10.多个条件的 AND(&&)运算符

如果仅在变量为 true 的情况下才调用函数,则可以使用 && 运算符。

  1. //Longhand
  2. if (test1) {
  3.   callMethod();
  4. }
  5. //Shorthand
  6. test1 && callMethod();

11.foreach 循环简写

这是迭代的常用简写技术之一。

  1. // Longhand
  2. for (var i = 0; i < testData.length; i++)
  3. // Shorthand
  4. for (let i in testData) or  for (let i of testData)

每个变量的数组

  1. function testData(element, index, array) {
  2.   console.log("test[" + index + "] = " + element);
  3. }
  4. [11, 24, 32].forEach(testData);
  5. // logs: test[0] = 11, test[1] = 24, test[2] = 32

12.return 中比较

我们也可以在 return 语句中使用比较。它将避免我们的 5 行代码,并将它们减少到 1 行。

  1. // Longhand
  2. let test;
  3. function checkReturn() {
  4.   if (!(test === undefined)) {
  5.     return test;
  6.   } else {
  7.     return callMe("test");
  8.   }
  9. }
  10. var data = checkReturn();
  11. console.log(data); //output test
  12. function callMe(val) {
  13.   console.log(val);
  14. }
  15. // Shorthand
  16. function checkReturn() {
  17.   return test || callMe("test");
  18. }

13.箭头函数

  1. //Longhand
  2. function add(a, b) {
  3.   return a + b;
  4. }
  5. //Shorthand
  6. const add = (a, b) => a + b;

更多示例。

  1. function callMe(name) {
  2.   console.log("Hello", name);
  3. }
  4. callMe = (name) => console.log("Hello", name);

14.短函数调用

我们可以使用三元运算符来实现这些功能。

  1. // Longhand
  2. function test1() {
  3.   console.log("test1");
  4. }
  5. function test2() {
  6.   console.log("test2");
  7. }
  8. var test3 = 1;
  9. if (test3 == 1) {
  10.   test1();
  11. } else {
  12.   test2();
  13. }
  14. // Shorthand
  15. (test3 === 1 ? test1 : test2)();

15. Switch 简写

我们可以将条件保存在键值对象中,并可以根据条件使用。

  1. // Longhand
  2. switch (data) {
  3.   case 1:
  4.     test1();
  5.     break;
  6.   case 2:
  7.     test2();
  8.     break;
  9.   case 3:
  10.     test();
  11.     break;
  12.   // And so on...
  13. }
  14. // Shorthand
  15. var data = {
  16.   1: test1,
  17.   2: test2,
  18.   3: test,
  19. };
  20. data[something] && data[something]();

16.隐式返回简写

使用箭头函数,我们可以直接返回值,而不必编写 return 语句。

  1. //longhand
  2. function calculate(diameter) {
  3.   return Math.PI * diameter
  4. }
  5. //shorthand
  6. calculate = diameter => (
  7.   Math.PI * diameter;
  8. )

17.小数基数指数

  1. // Longhand
  2. for (var i = 0; i < 10000; i++) { ... }
  3. // Shorthand
  4. for (var i = 0; i < 1e4; i++) {

18.默认参数值

  1. //Longhand
  2. function add(test1, test2) {
  3.   if (test1 === undefined) test1 = 1;
  4.   if (test2 === undefined) test2 = 2;
  5.   return test1 + test2;
  6. }
  7. //shorthand
  8. add = (test1 = 1, test2 = 2) => test1 + test2;
  9. add(); //output: 3

19.扩展运算符简写

  1. //longhand
  2. // joining arrays using concat
  3. const data = [1, 2, 3];
  4. const test = [4, 5, 6].concat(data);
  5. //shorthand
  6. // joining arrays
  7. const data = [1, 2, 3];
  8. const test = [4, 5, 6, ...data];
  9. console.log(test); // [ 4, 5, 6, 1, 2, 3]

对于克隆,我们也可以使用扩展运算符。

  1. //longhand
  2. // cloning arrays
  3. const test1 = [1, 2, 3];
  4. const test2 = test1.slice();
  5. //shorthand
  6. // cloning arrays
  7. const test1 = [1, 2, 3];
  8. const test2 = [...test1];

20.模板文字

如果您厌倦了在单个字符串中使用 + 来连接多个变量,那么这种简写可以消除您的头痛。

  1. //longhand
  2. const welcome = "Hi " + test1 + " " + test2 + ".";
  3. //shorthand
  4. const welcome = `Hi ${test1} ${test2}`;

21.多行字符串简写

当我们在代码中处理多行字符串时,可以使用以下功能:

  1. //longhand
  2. const data =
  3.   "abc abc abc abc abc abc\n\t" +
  4.   "test test,test test test test\n\t";
  5. //shorthand
  6. const data = `abc abc abc abc abc abc
  7.          test test,test test test test`;

22.对象属性分配

  1. let test1 = "a";
  2. let test2 = "b";
  3. //Longhand
  4. let obj = { test1: test1, test2: test2 };
  5. //Shorthand
  6. let obj = { test1, test2 };

23.将字符串转换成数字

  1. //Longhand
  2. let test1 = parseInt("123");
  3. let test2 = parseFloat("12.3");
  4. //Shorthand
  5. let test1 = +"123";
  6. let test2 = +"12.3";

24.用解构简写

  1. //longhand
  2. const test1 = this.data.test1;
  3. const test2 = this.data.test2;
  4. const test2 = this.data.test3;
  5. //shorthand
  6. const { test1, test2, test3 } = this.data;

25.用 Array.find 简写

当我们确实有一个对象数组并且我们想要根据对象属性查找特定对象时,find 方法确实很有用。

  1. const data = [
  2.   {
  3.     type: "test1",
  4.     name: "abc",
  5.   },
  6.   {
  7.     type: "test2",
  8.     name: "cde",
  9.   },
  10.   {
  11.     type: "test1",
  12.     name: "fgh",
  13.   },
  14. ];
  15. function findtest1(name) {
  16.   for (let i = 0; i < data.length; ++i) {
  17.     if (data[i].type === "test1" && data[i].name === name) {
  18.       return data[i];
  19.     }
  20.   }
  21. }
  22. //Shorthand
  23. filteredData = data.find(
  24.   (data) => data.type === "test1" && data.name === "fgh"
  25. );
  26. console.log(filteredData); // { type: 'test1', name: 'fgh' }

26.查找条件简写

如果我们有代码来检查类型,根据类型需要调用不同的方法,我们可以选择使用多个 else ifs 或者 switch,但是如果我们有比这更好的简写方法呢?

  1. // Longhand
  2. if (type === "test1") {
  3.   test1();
  4. } else if (type === "test2") {
  5.   test2();
  6. } else if (type === "test3") {
  7.   test3();
  8. } else if (type === "test4") {
  9.   test4();
  10. } else {
  11.   throw new Error("Invalid value " + type);
  12. }
  13. // Shorthand
  14. var types = {
  15.   test1: test1,
  16.   test2: test2,
  17.   test3: test3,
  18.   test4: test4,
  19. };
  20. var func = types[type];
  21. !func && throw new Error("Invalid value " + type);
  22. func();

27.按位索引简写

当我们遍历数组以查找特定值时,我们确实使用 indexOf() 方法,如果找到更好的方法该怎么办?让我们看看这个例子。

  1. //longhand
  2. if (arr.indexOf(item) > -1) {
  3.   // item found
  4. }
  5. if (arr.indexOf(item) === -1) {
  6.   // item not found
  7. }
  8. //shorthand
  9. if (~arr.indexOf(item)) {
  10.   // item found
  11. }
  12. if (!~arr.indexOf(item)) {
  13.   // item not found
  14. }

按位(〜)运算符将返回除-1 以外的任何值的真实值。否定它就像做 ~~ 一样简单。另外,我们也可以使用 include() 函数:

  1. if (arr.includes(item)) {
  2.   // true if the item found
  3. }

28.Object.entries()

此函数有助于将对象转换为对象数组。

  1. const data = { test1: "abc", test2: "cde", test3: "efg" };
  2. const arr = Object.entries(data);
  3. console.log(arr);
  4. /** Output:
  5. [ [ 'test1', 'abc' ],
  6.   [ 'test2', 'cde' ],
  7.   [ 'test3', 'efg' ]
  8. ]
  9. **/

29.Object.values()

这也是 ES8 中引入的一项新功能,该功能执行与 Object.entries() 类似的功能,但没有关键部分:

  1. const data = { test1: "abc", test2: "cde" };
  2. const arr = Object.values(data);
  3. console.log(arr);
  4. /** Output:
  5. [ 'abc', 'cde']
  6. **/

30.双按位简写

双重 NOT 按位运算符方法仅适用于 32 位整数)

  1. // Longhand
  2. Math.floor(1.9) === 1; // true
  3. // Shorthand
  4. ~~1.9 === 1; // true

31.重复一个字符串多次

要一次又一次地重复相同的字符,我们可以使用 for 循环并将它们添加到同一循环中,但是如果我们有一个简写方法呢?

  1. //longhand
  2. let test = "";
  3. for (let i = 0; i < 5; i++) {
  4.   test += "test ";
  5. }
  6. console.log(str); // test test test test test
  7. //shorthand
  8. "test ".repeat(5);

32.在数组中查找最大值和最小值

  1. const arr = [1, 2, 3];
  2. Math.max(…arr); // 3
  3. Math.min(…arr); // 1

33.从字符串中获取字符

  1. let str = 'abc';
  2. //Longhand
  3. str.charAt(2); // c
  4. //Shorthand
  5. Note: If we know the index of the array then we can directly use index insted of character.If we are not sure about index it can throw undefined
  6. str[2]; // c

34.数学指数幂函数的简写

  1. //longhand
  2. Math.pow(2, 3); // 8
  3. //shorthand
  4. 2 ** 3; // 8
原文作者:Atit
翻译:张张


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

js中for循环优化总结_如何提高程序的执行效率

在程序开发中,经常会使用到for循环的,但是很多人写的for循环效率都是比较低的,下面就举例说明,并总结优化for循环的方法,来提高我们程序的执行效率。

网站打开速度优化_如何提高网页访问速度技巧方法总结

网站的加载速度不仅影响着用户体验,也会影响搜索引擎的排名,在百度推出“闪电算法”以来,将网站首屏打开速度被列入优化排名行列,作为前端开发的我们需要如果来优化网站的打开速度呢?下面就整理挖掘出很多细节上可以提升性能的东西分享给大家

JS性能优化之文档片段createDocumentFragment

DocumentFragments是DOM节点。它们不是主DOM树的一部分。通常的用例是创建文档片段,将元素附加到文档片段,然后将文档片段附加到DOM树。在DOM树中,文档片段被其所有的子元素所代替。因为文档片段存在于内存中,并不在DOM树中

深入浅出代码优化﹣if/else

对于代码裡面的 if else,我们可以使用逻辑判断式,或更好的三元判断式来优化代码。除了可以降低维护项目的成本之外,还可以提升代码可读性。就让我们从最简单的 if else 例子开始吧。

微信小程序性能优化入门指南

小程序从发布到现在也已经有将近两年的时间,越来越来多的公司开始重视小程序生态带来的流量,今年也由于小程序平台对外能力的越来越多的开放以及小程序平台的自身优化,越来越多的开发者也自主的投入到小程序的开发当中

网络串流播放_HTML5如何优化视频文件以便在网络上更快地串流播放

无论你正在将 GIF 动图转换为 MP4 视频,还是手头已经有一大堆 MP4 视频,你都可以优化文件结构,以使得这些视频更快地加载和播放。通过重组 atoms 将 moov 放到文件开头,浏览器可以避免发送额外的 HTTP range request 请求来搜寻和定位 moovatom

​web项目优化_Web 服务器性能与站点访问性能优化

要优化 Web 服务器的性能,我们先来看看 Web 服务器在 web 页面处理上的步骤:Web 浏览器向一个特定的服务器发出 Web 页面请求; Web 服务器接收到 web 页面请求后,寻找所请求的 web 页面,并将所请求的 Web 页面传送给 Web 浏览器; 显示出来

前端性能优化之重排和重绘

浏览器下载完页面所有的资源后,就要开始构建DOM树,于此同时还会构建渲染树(Render Tree)。(其实在构建渲染树之前,和DOM树同期会构建Style Tree。DOM树与Style Tree合并为渲染树)

微信小程序代码优化总汇

写篇文章的目的,是以开放小程序代码的层面的优化。包括:条件判断将wx:if换成了hidden 、页面跳转请销毁之前使用的资源、列表的局部更新、小程序中多张图片懒加载方案、Input状态下隐藏input,应预留出键盘收起的时间

我是如何将页面加载时间从6S降到2S的?

生活在信息爆炸的今天,我们每天不得不面对和过滤海量的信息--无疑是焦躁和浮动的,这就意味着用户对你站点投入的时间可能是及其吝啬的(当然有一些刚需站点除外)。如何给用户提供迅速的响应就显得十分重要了

点击更多...

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