javascript 代码

by Arthur Arakelyan

通过亚瑟·阿拉克利安(Arthur Arakelyan)

如何使您JavaScript代码简单易读 (How to keep your JavaScript code simple and easy to read)

There are many ways to solve the same problem, but some solutions are complex, and some are even ridiculous. In this article, I want to talk about bad and good solutions for the same problems.

解决同一问题的方法有很多,但有些解决方案很复杂,有些甚至很荒谬。 在本文中,我想谈谈针对相同问题的不好的解决方案。

Let’s start with the problem that requires us to remove duplicate values from an array.

让我们从需要从数组中删除重复值的问题开始。

复杂-使用forEach删除重复项 (Complex - Removing duplicates using forEach)

First, we create a new empty array, then we use the forEach() method to execute a provided function once for each array element. Eventually, we check if the value doesn’t exist in the new array, and if not, we add it.

首先,我们创建一个新的空数组,然后使用forEach()方法为每个数组元素执行一次提供的函数。 最终,我们检查新数组中是否不存在该值,如果不存在,则添加它。

function removeDuplicates(arr) {     const uniqueVals = [];      arr.forEach((value,index) => {            if(uniqueVals.indexOf(value) === -1) {           uniqueVals.push(value);       }     });  return uniqueVals;}

简单-使用过滤器删除重复项 (Simple - Removing duplicates using filter)

The filter method creates a new array with all elements that pass the test implemented by the provided function. Basically, we iterate over the array and, for each element, check if the first position of this element in the array is equal to the current position. Of course, these two positions are different for duplicate elements.

filter方法创建一个新数组,其中所有元素都通过了由提供的功能实现的测试。 基本上,我们遍历数组,并针对每个元素检查此元素在数组中的第一个位置是否等于当前位置。 当然,对于重复元素,这两个位置是不同的。

function removeDuplicates(arr) {  return arr.filter((item, pos) => arr.indexOf(item) === pos)}

简单-使用Set删除重复项 (Simple - Removing duplicates using Set)

ES6 provides the Set object, which makes things a whole lot easier. Set allows only unique values, so when you pass in an array, it removes any duplicate values.

ES6提供了Set对象,这使事情变得非常容易。 Set仅允许唯一值,因此在传递数组时,它会删除所有重复值。

However, if you need an array with unique elements, why not use Set right from the beginning?

但是,如果需要具有唯一元素的数组,为什么不从一开始就使用Set

function removeDuplicates(arr) {   return [...new Set(arr)];}

Let’s move on and solve the second problem which requires us to write a function that takes an array of distinct non-negative integers, make them consecutive, and return the count of missing numbers.

让我们继续解决第二个问题,该问题需要我们编写一个函数,该函数接受一组不同的非负整数,使其连续,并返回缺失数的计数。

For const arr = [4, 2, 6, 8], the output should becountMissingNumbers(arr) = 3

对于const arr = [4, 2, 6, 8] countMissingNumbers(arr) = 3 const arr = [4, 2, 6, 8] ,输出应为countMissingNumbers(arr) = 3

As you can see 3, 5and 7 are missing

正如你所看到的357失踪

复杂-使用sort和for循环求解 (Complex - Solving by using sort and for loop)

To obtain the smallest and largest numbers we need to sort them in ascending order, and for that purpose, we use sort method. Then we loop from the smallest number to the largest number. Each time, we check whether a sequential number exists in the array or not, and if not we increase the counter.

为了获得最小和最大的数字,我们需要按升序它们进行排序 ,为此,我们使用sort方法。 然后,我们从最小的数字循环到最大的数字。 每次,我们检查数组中是否存在序列号,否则,我们增加计数器。

function countMissingNumbers(arr) {    arr.sort((a,b) => a-b);        let count = 0;        const min = arr[0];        const max = arr[arr.length-1];    for (i = min; i<max; i++) {      if (arr.indexOf(i) === -1) {          count++;               }          }            return count;}

简单-使用Math.max和Math.min解决 (Simple - Solving by using Math.max and Math.min)

This solution has a simple explanation: the Math.max() function returns the largest number in the array and the Math.min() returns the smallest number in the array.

该解决方案有一个简单的解释: Math.max()函数返回数组中的最大数字,而Math.min()返回数组中的最小数字。

First, we find how many numbers would be in the array if there weren’t missing numbers. For that, we use the following formula maxNumber - minNuber + 1, and the difference between the result of this and the array length will give us the count of missing numbers.

首先,我们发现如果不缺少数字,数组中将有多少个数字。 为此,我们使用以下公式maxNumber - minNuber + 1 ,其结果与数组长度之间的差将为我们提供缺失数的计数。

function countMissingNumbers(arr) {      return Math.max(...arr) - Math.min(...arr) + 1 - arr.length;}

The last problem I want to bring as an example is to check whether the string is a palindrome or not.

我想举一个例子的最后一个问题是检查字符串是否是回文

*A palindrome is a string that reads the same left-to-right and right-to-left.

*回文集是从左到右和从右到左读取相同字符串的字符串。

复杂-使用for循环进行检查 (Complex - Checking By using for loop)

In this option, we loop over the string starting from the first character until half of the string length. The index of the last character in a string is string.length-1, the second to last character is string.length-2, and so on. So here we check whether the character at the specified index from the start is equal to the character at the specified index at the end. If they are not equal, we return false.

在此选项中,我们从第一个字符开始直到字符串长度的一半遍历字符串。 字符串中最后一个字符的索引是string.length-1,倒数第二个字符是string.length-2,依此类推。 因此,这里我们从头开始检查指定索引处的字符是否等于末尾在指定索引处的字符。 如果它们不相等,则返回false。

function checkPalindrome(inputString) {    let length = inputString.length   for (let i =0; i<length / 2; i++) {        if (inputString[i] !== inputString[length - 1 -i]) {             return false                }   }  return true}

简单-通过使用反向和联接进行检查 (Simple - Checking by using reverse and join)

I think that this simple solution doesn't require an explanation, as it speaks for itself. We simply create an array from the string using the spread operator, then reverse the array, then turn it into a string again using the join method and compare it with the original string.

我认为这个简单的解决方案不需要说明,因为它说明了一切。 我们只需使用spread运算符从字符串创建一个数组,然后反转该数组,然后使用join方法将其再次转换为字符串并将其与原始字符串进行比较。

function checkPalindrome(string) {   return string === [...string].reverse().join('');}

把事情简单化! (Keep it simple!)

Why complicate when there are simpler ways? I hope you found this article interesting. Have a good day and try not to complicate simple things in life as well :)

当有更简单的方法时,为什么会变得复杂? 希望您觉得这篇文章有趣。 祝您有美好的一天,也不要让生活中的简单事情变得复杂:)

Thanks for your claps ?

谢谢你的鼓掌?

翻译自: https://www.freecodecamp.org/news/how-to-keep-your-javascript-code-simple-and-easy-to-read-bff702523e7c/

javascript 代码

javascript 代码_如何使您JavaScript代码简单易读相关推荐

  1. javascript 代码_如何使您JavaScript代码保持简单并提高其可读性

    javascript 代码 by Leonardo Lima 莱昂纳多·利马(Leonardo Lima) 如何使您JavaScript代码保持简单并提高其可读性 (How to keep your ...

  2. javascript控制台_如何使您JavaScript控制台静音

    javascript控制台 by Shakeel Mohamed Shakeel Mohamed着 如何使您JavaScript控制台静音 (How to silence your JavaScrip ...

  3. 存储过程可重用的代码块_如何使您的代码可重用

    可重用代码不是通用代码 Image Credits: Pixabay.com 可重用的代码作为解决所有软件问题的一站式解决方案,是一个危险的神话. 让我解释一下原因. 假设您正在编写软件库. 您脑中冒 ...

  4. javascript关键字_让我们揭开JavaScript的“ new”关键字的神秘面纱

    javascript关键字 by Cynthia Lee 辛西娅·李(Cynthia Lee) 让我们揭开JavaScript的" new"关键字的神秘面纱 (Let's demy ...

  5. javascript 图表_我如何使用JavaScript数据透视表和图表库分析开发人员趋势

    javascript 图表 Hi, dev community! 嗨,开发者社区! Today I'd like to share my experience of analyzing develop ...

  6. javascript 框架_我们仍然需要JavaScript框架吗?

    javascript 框架 by Luke Joliat 卢克·乔里亚特(Luke Joliat) 我们仍然需要JavaScript框架吗? (Do we still need JavaScript ...

  7. 一段堆栈溢出的代码_为什么堆栈溢出的代码片段会破坏您的项目

    一段堆栈溢出的代码 Stack Overflow has been the saviour of many programmers, including me. Some of us have nev ...

  8. 史上最烂代码_历史上最大的代码库

    史上最烂代码 Here's a diagram of the biggest codebases in history, as measured by lines of code: 这是历史上最大的代 ...

  9. vscode中怎样格式化js代码_如何在Visual Studio代码(VSCode)中格式化代码

    回答(30) 2 years ago 对于那些想要自定义要格式化的JavaScript文件的人,可以使用 JSfiles 属性上的任何扩展名同样适用于HTML . { "beautify.o ...

最新文章

  1. 中文金额大写转换处理
  2. 赛灵思Zynq-7000 可扩展处理平台(EPP)介绍
  3. android 控件id为0,Android Studio错误:(3,0)未找到ID为“com.android.application”的插件...
  4. 【经典面试题一】最长公共子序列(经典动态规划题)
  5. 计算机微格教学心得体会,微格教学心得体会
  6. JQuery DOM基本操作
  7. wxWidgets:wxModule类用法
  8. 跟随光标下划线导航插件
  9. 校验值的计算----移位算法
  10. C++设计模式-面向对象程序设计要点以及封装性特点
  11. Revit二次开发之“为Ribbon设置快捷键”
  12. CSS-标准盒模型和怪异盒模型box-sizing
  13. javascript 内置对象学习 笔记:
  14. Ural 1780 Gray Code 乱搞暴力
  15. Hibernate Session get()vs load()实例差异
  16. jdk1.8下载安装
  17. eclipse 主题设置
  18. 酒浓码浓 - js / 前端 / 支付宝,微信合并二维码功能
  19. androidstudio上传自己的lib到Jcenter
  20. 基于Matlab的DSB调制解调,课程设计(论文)-基于MATLAB的DSB调制与解调分析.doc

热门文章

  1. log4j的使用 20220228
  2. 唯一约束 mysql
  3. 常用控件 winform
  4. 四窗口卖票 自己的票
  5. 字节流读数据 一次读一个字节
  6. pptx给幻灯片添加内容
  7. javascript 西瓜一期 11 二进制的数数进位解析
  8. Last_Error: Slave SQL thread retried transaction 10 time(s) in vain, giving up导致主从不同步的解决方法
  9. mongodb自动备份脚本
  10. godaddy最新域名优惠码永久有效