javascript 代码_如何使您JavaScript代码简单易读

 2023-09-06 阅读 22 评论 0

摘要: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 e

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 代码

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/3/7317.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息