search
HomeWeb Front-endHTML TutorialJavaScript学习笔记:取数组中最大值和最小值_html/css_WEB-ITnose

在实际业务中有的时候要取出数组中的最大值或最小值。但在数组中并没有提供 arr.max() 和 arr.min() 这样的方法。那么是不是可以通过别的方式实现类似这样的方法呢?那么今天我们就来整理取出数组中最大值和最小值的一些方法。

取数组中最大值

可以先把思路理一下:

  • 将数组中第一个元素赋值给一个变量,并且把这个变量作为最大值;
  • 开始遍历数组,从第二个元素开始依次和第一个元素进行比较
  • 如果当前的元素大于当前的最大值,就把当前的元素值赋值给最大值
  • 移动到下一个元素,继续按前面一步操作
  • 当数组元素遍历结束时,这个变量存储的就是最大值

代码如下:

Array.prototype.max = function () {    // 将数组第一个元素的值赋给max    var max = this[0];    // 使用for 循环从数组第一个值开始做遍历    for (var i = 1; i < this.length; i++) {        // 如果元素当前值大于max,就把这个当前值赋值给max        if (this[i] > max) {            max = this[i];        }    }    // 返回最大的值    return max;}

来看一个示例:

var arr = [1,45,23,3,6,2,7,234,56];arr.max(); // 234

上面的示例,数组中都是数值,那么如果数组中不全是数值会是一个什么样的效果呢?来测试一下先:

var arr = [1,45,23,3,6,2,7,234,56,'2345','a','c'];arr.max(); // 'c'

这并不是我们想要的结果吧。( 此处跪求解决方案 )

通过前段时间的学习,都知道 for 循环性能要比 forEach() 差,那可以将上面的方法改成 forEach() 方法:

Array.prototype.max = function (){    var max = this[0];    this.forEach (function(ele,index,arr){        if(ele > max) {            max = ele;        }    })    return max;}var arr = [1,45,23,3,6,2,7,234,56];arr.max(); // 234

取数组中最小值

类似取最大值的思路一样,我们可以很轻松的实现 arr.min() 方法,取出数组中的最小值:

Array.prototype.min = function () {    var min = this[0];    this.forEach(function(ele, index,arr) {        if(ele < min) {            min = ele;        }    })    return min;}var arr = [1,45,23,3,6,2,7,234,56];arr.min(); // 1

其他方法

除了上面的方案,还可以有其他方法,比如使用数组的 reduce() 方法。回忆前面的学过的知识, reduce() 方法 可以接收一个回调函数 callbackfn ,可以在这个回调函数中拿数组中的初始值( preValue )与数组中当前被处理的数组项( curValue )做比较,如果 preValue 大于 curValue 值返回 preValue ,反之返回 curValue 值,依此类推取出数组中最大值:

Array.prototype.max = function() {    return this.reduce(function(preValue, curValue,index,array) {        return preValue > curValue ? preValue : curValue;    })}var arr = [1,45,23,3,6,2,7,234,56];arr.max(); // 234

同样的也可以使用类似的方法实现 arr.mix() 方法,取出数组中的最小值:

Array.prototype.min = function() {    return this.reduce(function(preValue, curValue,index,array) {        return preValue > curValue ? curValue : preValue;    })}var arr = [1,45,23,3,6,2,7,234,56];arr.min(); // 1

内置函数 Math.max() 和 Math.min() 方法

对于纯数字数组,可以使用JavaScript中的内置函数 Math.max() 和 Math.min() 方法。使用这两个内置函数可以分别找出数组中的最大值和最上值。在使用这两种内置函数取出数组最大和最小值之前,先学习一下 Math.max() 和 Math.min() 两个函数。

Math.max()

Math.max() 函数返回一组数中的最大值。

Math.max(1,32,45,31,3442,4); // 3442Math.max(10, 20);   //  20Math.max(-10, -20); // -10Math.max(-10, 20);  //  20

Math.min()

Math.min() 函数和 Math.max() 函数刚好相反,其会返回一组数中的最小值:

Math.min(10,20); //10Math.min(-10,-20); //-20Math.min(-10,20); //-10Math.min(1,32,45,31,3442,4); //1

这些函数如果没有参数,则结果为 -Infinity ;如果有任一参数不能被转换为数值,则结果为 NaN 。最主要的是这两个函数对于数字组成的数组是不能直接使用的。但是,这有一些类似地方法。

Function.prototype.apply()让你可以使用提供的this与参数组与的数组来调用参数。

// 取出数组中最大值Array.max = function( array ){    return Math.max.apply( Math, array );}; // 取出数组中最小值Array.min = function( array ){    return Math.min.apply( Math, array );};var arr = [1,45,23,3,6,2,7,234,56];Array.max(arr); // 234Array.min(arr); // 1

Math 对象也是一个对象,可以使用对象的字面量来写,如:

Array.prototype.max = function () {    return Math.max.apply({},this);}Array.prototype.min = function () {    return Math.min.apply({},this);}var arr = [1,45,23,3,6,2,7,234,56];arr.max(); // 234arr.min(); // 1

其实还有更简单的方法。基于ES2015的方法来实现此功能,是使用 展开运算符 :

var numbers = [1, 2, 3, 4];Math.max(...numbers) // 4Math.min(...numbers) // 1

此运算符使数组中的值在函数调用的位置展开。

总结

这篇文章整理了几个从数组中取出最大值和最小值的方法。这几个方法都只是会对于数字数组,而对于数组中包含其他数据类型时,如何只取出最大的数值和最小的数值(如果您知道如何实现,还望指点迷津)。而这几种方法当中,使用JavaScript的内置函数 Math.max() 和 Math.min() 配合 Function.prototype.apply() 可以轻松取出数组中的最大值和最小值。当然最最简单的要当数ES2015中使用展示运算符的方法。如果大家还有更好的方案,希望能在下面的评论中与我们一起分享。

参考资料

  • 数组取最大值与最小值
  • JavaScript: min & max Array values?
  • 计算数组中的最大值/最小值

初学者学习笔记,如有不对,还希望高手指点。如有造成误解,还希望多多谅解。

大漠

常用昵称“大漠”,W3CPlus创始人,目前就职于手淘。中国Drupal社区核心成员之一。对HTML5、CSS3和Sass等前端脚本语言有非常深入的认识和丰富的实践经验,尤其专注对CSS3的研究,是国内最早研究和使用CSS3技术的一批人。CSS3、Sass和Drupal中国布道者。2014年出版《 图解CSS3:核心技术与案例实战 》。

Statement
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
The Future of HTML, CSS, and JavaScript: Web Development TrendsThe Future of HTML, CSS, and JavaScript: Web Development TrendsApr 19, 2025 am 12:02 AM

The future trends of HTML are semantics and web components, the future trends of CSS are CSS-in-JS and CSSHoudini, and the future trends of JavaScript are WebAssembly and Serverless. 1. HTML semantics improve accessibility and SEO effects, and Web components improve development efficiency, but attention should be paid to browser compatibility. 2. CSS-in-JS enhances style management flexibility but may increase file size. CSSHoudini allows direct operation of CSS rendering. 3.WebAssembly optimizes browser application performance but has a steep learning curve, and Serverless simplifies development but requires optimization of cold start problems.

HTML: The Structure, CSS: The Style, JavaScript: The BehaviorHTML: The Structure, CSS: The Style, JavaScript: The BehaviorApr 18, 2025 am 12:09 AM

The roles of HTML, CSS and JavaScript in web development are: 1. HTML defines the web page structure, 2. CSS controls the web page style, and 3. JavaScript adds dynamic behavior. Together, they build the framework, aesthetics and interactivity of modern websites.

The Future of HTML: Evolution and Trends in Web DesignThe Future of HTML: Evolution and Trends in Web DesignApr 17, 2025 am 12:12 AM

The future of HTML is full of infinite possibilities. 1) New features and standards will include more semantic tags and the popularity of WebComponents. 2) The web design trend will continue to develop towards responsive and accessible design. 3) Performance optimization will improve the user experience through responsive image loading and lazy loading technologies.

HTML vs. CSS vs. JavaScript: A Comparative OverviewHTML vs. CSS vs. JavaScript: A Comparative OverviewApr 16, 2025 am 12:04 AM

The roles of HTML, CSS and JavaScript in web development are: HTML is responsible for content structure, CSS is responsible for style, and JavaScript is responsible for dynamic behavior. 1. HTML defines the web page structure and content through tags to ensure semantics. 2. CSS controls the web page style through selectors and attributes to make it beautiful and easy to read. 3. JavaScript controls web page behavior through scripts to achieve dynamic and interactive functions.

HTML: Is It a Programming Language or Something Else?HTML: Is It a Programming Language or Something Else?Apr 15, 2025 am 12:13 AM

HTMLisnotaprogramminglanguage;itisamarkuplanguage.1)HTMLstructuresandformatswebcontentusingtags.2)ItworkswithCSSforstylingandJavaScriptforinteractivity,enhancingwebdevelopment.

HTML: Building the Structure of Web PagesHTML: Building the Structure of Web PagesApr 14, 2025 am 12:14 AM

HTML is the cornerstone of building web page structure. 1. HTML defines the content structure and semantics, and uses, etc. tags. 2. Provide semantic markers, such as, etc., to improve SEO effect. 3. To realize user interaction through tags, pay attention to form verification. 4. Use advanced elements such as, combined with JavaScript to achieve dynamic effects. 5. Common errors include unclosed labels and unquoted attribute values, and verification tools are required. 6. Optimization strategies include reducing HTTP requests, compressing HTML, using semantic tags, etc.

From Text to Websites: The Power of HTMLFrom Text to Websites: The Power of HTMLApr 13, 2025 am 12:07 AM

HTML is a language used to build web pages, defining web page structure and content through tags and attributes. 1) HTML organizes document structure through tags, such as,. 2) The browser parses HTML to build the DOM and renders the web page. 3) New features of HTML5, such as, enhance multimedia functions. 4) Common errors include unclosed labels and unquoted attribute values. 5) Optimization suggestions include using semantic tags and reducing file size.

Understanding HTML, CSS, and JavaScript: A Beginner's GuideUnderstanding HTML, CSS, and JavaScript: A Beginner's GuideApr 12, 2025 am 12:02 AM

WebdevelopmentreliesonHTML,CSS,andJavaScript:1)HTMLstructurescontent,2)CSSstylesit,and3)JavaScriptaddsinteractivity,formingthebasisofmodernwebexperiences.

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools