Home Web Front-end JS Tutorial Get the largest and smallest element in Number

Get the largest and smallest element in Number

Jun 11, 2018 am 10:00 AM
js

This time I will introduce to you how to get the largest and smallest elements in Number. What are the precautions for getting the largest and smallest elements in Number? The following is a practical case, let's take a look.

1. Do not use any library function

The code is as follows:

function findMax1 (arr) {
  let result = 0;
  if (Array.isArray(arr)) {
    for (let i = 0; i < arr.length; i++) {
      result = arr[i] > result ? arr[i] : result;
    }
    
    return result;
  } else {
    console.error('The parameter arr is not an array');
    return;
  }
}
Copy after login

Explanation:

Use a variable result to store the maximum value. Traverse the array to be searched. If the currently traversed element is greater than result, assign this element to result.

2. Use Array.reduce()

The code is as follows:

function findMax2 (arr) {
  let result = 0;
  if (Array.isArray(arr)) {
    result = arr.reduce((a, b) => {
      return a > b ? a : b;
    }, 0);
    
    return result;
  } else {
    console.error('The parameter arr is not an array');
    return;
  }
}
Copy after login

Explanation:

The reduce method is through a function , for an accumulator and each element in the array, ultimately reducing an array to a single value.

reduce accepts two parameters:

The first one is callback, which is the function mentioned earlier. It has four parameters:

  1. accumulator: Accumulator, which is the result of the last callback run. If initialValue is provided, then the first time is initialValue;

  2. currentValue: the elements of the currently traversed array;

  3. currentIndex: the currently traversed The index of the array element, starting from 0. If initialValue is provided, it starts from 1;

  4. array: the array to which reduce is currently applied.

The second is initialValue, which is an initial value and is used as the first actual parameter of the first run of the callback function. This is optional. Please note here that if this parameter is not provided and is applied to an empty array, an error will be reported.

Then the meaning of the above code is that each time the array is traversed for comparison, the larger one is retained, that is, the accumulator, and used for the next comparison with the array elements. In the end, only this value is left, which is the maximum value.

3. Use Apply and Math.max()

The code is as follows:

function findMax3 (arr) {
  let result = 0;
  if (Array.isArray(arr)) {
    result = Math.max.apply(null, arr);
    
    return result;
  } else {
    console.error('The parameter arr is not an array');
    return;
  }
}
Copy after login

Explanation:

apply explanation is slightly clearer Complex, no further explanation required.

It accepts two parameters, the first is thisArg and the second is argsArray. Both are optional. To put it simply, when using a function, the parameters are passed in as an array.

4. Only use Math.max()

The code is as follows:

function findMax4 (arr) {
  let result = 0;
  if (Array.isArray(arr)) {
    result = Math.max(...arr);
    
    return result;
  } else {
    console.error('The parameter arr is not an array');
    return;
  }
}
Copy after login

Explanation:

Based on the previous solution The idea is that in ES6, there is a spread operator (...) that can separate the elements in an array into a comma-separated sequence. Just meets the needs of the Math.max() function.

Let me introduce to you some knowledge points related to number, Math and arrays in JS

1. Number object.

How to create a Number object:

Method 1:

var variable = new Number (number)

Method 2:

var variable = number;

Commonly used method:

toString() Convert the number into a string in the specified base form. (Enter a number and it will be converted into a number, number.toString(2))

toFixed() specifies that decimal places are retained and it also has a rounding function.

2. Math

Commonly used methods of Math objects:

ceil Round up

floor() Round down

random() random number method // The pseudo-random number generated is between 0 and 1 (including 0, excluding 1),

round rounding

3. Array array object:

Method 1 to create an array:

var variable name = new Array(); Create an array with a length of 0.

Method 2:

var variable name = new Array(length) creates an array object of specified length.

Method 3:

var variable name = new Array("Element 1", "Element 2"...); Create an array object by specifying elements in the array.

Method 4:

var variable name = ["Element 1", "Element 2"...];

Details to note for arrays:

1. The length of an array can change in javascript.

var arr = new Array(); //创建了一个长度为0的数组对象。
arr[100] = 10;
document.write("arr长度:"+arr.length+"<br/>");
var arr2 = new Array("狗娃","狗剩","铁蛋");
arr2 = ["狗娃","狗剩","铁蛋","张三"];
document.write("arr2长度:"+arr2.length+"<br/>");
Copy after login

3.1数字的方法

a、concat把arr1与arr2的数组元素组成一个新的数组返回。  
arr1 = arr1.concat(arr2);
Copy after login

b、join使用指定的分隔符把数组中的元素拼装成一个字符串返回。

var elements = arr1.join(",");
Copy after login

c、pop :移除数组中的最后一个元素并返回该元素。

d、push:将新元素添加到一个数组中,并返回数组的新长度值。

arr1.push("你好");
Copy after login

e、reverse(); 翻转数组的元素

f、slice指定数组 的开始索引值与结束索引值截取数组的元素,并且返回子数组。(包头不包尾)

var subArr = arr1.slice(1,2);
Copy after login

g、sort排序,排序的时候一定要传入排序的方法。(不传时默认是按照ASCII表排列)

arr1 = [19,1,20,5];
arr1.sort(sortNumber); //排序,排序的时候一定要传入排序的方法。
function sortNumber(num1,num2){ 
return num1-num2;
}
Copy after login

h、splice第一个参数是开始删除元素的 索引值, 第二参数是删除元素的个数,往后的数据就是插入的元素(也可以不写)。

arr1.splice(1,1,"张三","李四","王五");
Copy after login

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

微信小程序调用相机拍照

JS使用createElement()动态添加HTML

The above is the detailed content of Get the largest and smallest element in Number. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use JS and Baidu Maps to implement map pan function How to use JS and Baidu Maps to implement map pan function Nov 21, 2023 am 10:00 AM

How to use JS and Baidu Map to implement map pan function Baidu Map is a widely used map service platform, which is often used in web development to display geographical information, positioning and other functions. This article will introduce how to use JS and Baidu Map API to implement the map pan function, and provide specific code examples. 1. Preparation Before using Baidu Map API, you first need to apply for a developer account on Baidu Map Open Platform (http://lbsyun.baidu.com/) and create an application. Creation completed

Recommended: Excellent JS open source face detection and recognition project Recommended: Excellent JS open source face detection and recognition project Apr 03, 2024 am 11:55 AM

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages ​​and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Dec 17, 2023 pm 06:55 PM

Essential tools for stock analysis: Learn the steps to draw candle charts in PHP and JS. Specific code examples are required. With the rapid development of the Internet and technology, stock trading has become one of the important ways for many investors. Stock analysis is an important part of investor decision-making, and candle charts are widely used in technical analysis. Learning how to draw candle charts using PHP and JS will provide investors with more intuitive information to help them make better decisions. A candlestick chart is a technical chart that displays stock prices in the form of candlesticks. It shows the stock price

How to create a stock candlestick chart using PHP and JS How to create a stock candlestick chart using PHP and JS Dec 17, 2023 am 08:08 AM

How to use PHP and JS to create a stock candle chart. A stock candle chart is a common technical analysis graphic in the stock market. It helps investors understand stocks more intuitively by drawing data such as the opening price, closing price, highest price and lowest price of the stock. price fluctuations. This article will teach you how to create stock candle charts using PHP and JS, with specific code examples. 1. Preparation Before starting, we need to prepare the following environment: 1. A server running PHP 2. A browser that supports HTML5 and Canvas 3

How to use JS and Baidu Map to implement map click event processing function How to use JS and Baidu Map to implement map click event processing function Nov 21, 2023 am 11:11 AM

Overview of how to use JS and Baidu Maps to implement map click event processing: In web development, it is often necessary to use map functions to display geographical location and geographical information. Click event processing on the map is a commonly used and important part of the map function. This article will introduce how to use JS and Baidu Map API to implement the click event processing function of the map, and give specific code examples. Steps: Import the API file of Baidu Map. First, import the file of Baidu Map API in the HTML file. This can be achieved through the following code:

How to use JS and Baidu Maps to implement map heat map function How to use JS and Baidu Maps to implement map heat map function Nov 21, 2023 am 09:33 AM

How to use JS and Baidu Maps to implement the map heat map function Introduction: With the rapid development of the Internet and mobile devices, maps have become a common application scenario. As a visual display method, heat maps can help us understand the distribution of data more intuitively. This article will introduce how to use JS and Baidu Map API to implement the map heat map function, and provide specific code examples. Preparation work: Before starting, you need to prepare the following items: a Baidu developer account, create an application, and obtain the corresponding AP

PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts Dec 18, 2023 pm 03:39 PM

With the rapid development of Internet finance, stock investment has become the choice of more and more people. In stock trading, candle charts are a commonly used technical analysis method. It can show the changing trend of stock prices and help investors make more accurate decisions. This article will introduce the development skills of PHP and JS, lead readers to understand how to draw stock candle charts, and provide specific code examples. 1. Understanding Stock Candle Charts Before introducing how to draw stock candle charts, we first need to understand what a candle chart is. Candlestick charts were developed by the Japanese

How to use JS and Baidu Maps to implement map polygon drawing function How to use JS and Baidu Maps to implement map polygon drawing function Nov 21, 2023 am 10:53 AM

How to use JS and Baidu Maps to implement map polygon drawing function. In modern web development, map applications have become one of the common functions. Drawing polygons on the map can help us mark specific areas for users to view and analyze. This article will introduce how to use JS and Baidu Map API to implement map polygon drawing function, and provide specific code examples. First, we need to introduce Baidu Map API. You can use the following code to import the JavaScript of Baidu Map API in an HTML file

See all articles