search
HomeWeb Front-endHTML TutorialJavaScript学习笔记:数组(八)_html/css_WEB-ITnose

很多时候需要累加数组项的得到一个值(比如说求和)。如果你碰到一个类似的问题,你想到的方法是什么呢?会不会和我一样,想到的就是使用 for 或 while 循环,对数组进行迭代,依次将他们的值加起来。比如:

var arr = [1,2,3,4,5,6];Array.prototype.sum = function (){    var sumResult = 0;    for (var i = 0; i < this.length; i++) {        sumResult += parseInt(this[i]);    }    return sumResult;}arr.sum(); // 21

或者

var arr =  [1,2,3,4,5,6];Array.prototype.sum = function () {    var sumResult = 0;    var i = this.length;    while (i--) {        sumResult += parseInt(this[i]);    }    return sumResult;}arr.sum(); // 21

那他们是不是最好的方案呢?先来看看他们所耗时间。

// 测试for和while循环实现数组求和的性能var arr = [1,2,3,4,5,6];// for循环console.time("forLoop");Array.prototype.forLoop = function (){    for (var i = 0; i < 10000; i++) {        var sumResult = 0;        for (var j = 0; j < this.length; j++) {            sumResult += parseInt(this[j]);        }    }    return sumResult;}arr.forLoop();console.log('最终的值:' + arr.forLoop()); // 21console.timeEnd("forLoop"); // 54.965ms

再来看看 while 循环所用时间:

var arry = [1,2,3,4,5,6];console.time("whileLoop");Array.prototype.whileLoop = function () {    for (var i = 0; i < 10000; i++) {        var sumResult = 0;        for (var j = 0; j < this.length; j++) {            sumResult += parseInt(this[j]);        }    }    return sumResult;}arry.whileLoop();console.log('最终的值:' + arry.whileLoop()); // 21console.timeEnd("whileLoop"); // 53.056ms

看看对比结果

循环类型 最终值(和) 所费时间
for 21 54.965ms
while 21 53.056ms

备注:数组 [1,2,3,4,5,6] 做了 10000 次循环的累加。

虽然上面使用 for 和 while 都能实现需要的效果,但在JavaScript中有没有更好的方案呢?回答是肯定的,在JavaScript中(ESMAScript 5)提供了另外两个数组的方法 reduce() 和 reduceRight() ,这两个数组会迭代数组的所有数组项,然后返回一个最终值。接下来的内容,主要来学习这两种方法。

reduce() 方法

reduce() 方法接收一个函数 callbackfn 作为累加器(accumulator),数组中的每个值(从左到右)开始合并,最终为一个值。

语法

array.reduce(callbackfn,[initialValue])

reduce() 方法接收 callbackfn 函数,而这个函数包含四个参数:

function callbackfn(preValue,curValue,index,array){}
  • preValue : 上一次调用回调返回的值,或者是提供的初始值(initialValue)
  • curValue : 数组中当前被处理的数组项
  • index : 当前数组项在数组中的索引值
  • array : 调用 reduce() 方法的数组

而 initialValue 作为第一次调用 callbackfn 函数的第一个参数。

reduce() 方法为数组中的每一个元素依次执行回调函数 callbackfn ,不包括数组中被删除或从未被赋值的元素,接受四个参数:初始值(或者上一次回调函数的返回值),当前元素值,当前索引,调用 reduce() 的数组。

回调函数第一次执行时, preValue 和 curValue 可以是一个值,如果 initialValue 在调用 reduce() 时被提供,那么第一个 preValue 等于 initialValue ,并且 curValue 等于数组中的第一个值;如果 initialValue 未被提供,那么 preValue 等于数组中的第一个值,`curValue等于数组中的第二个值。

来看一个示例:

var arr = [0,1,2,3,4];arr.reduce(function (preValue,curValue,index,array) {    return preValue + curValue;}); // 10

示例中的回调函数被执行四次,每次参数和返回的值如下:

preValue curValue index array 返回值
第一次回调 0 1 1 [0,1,2,3,4] 1
第二次回调 1 2 2 [0,1,2,3,4] 3
第三次回调 3 3 3 [0,1,2,3,4] 6
第四次回调 6 4 4 [0,1,2,3,4] 10

上面的示例 reduce() 方法没有提供 initialValue 初始值,接下来再上面的示例中,稍作修改,提供一个初始值,这个值为 5 。这个时候 reduce() 方法会执行五次回调,每次参数和返回的值如下:

var arr = [0,1,2,3,4];arr.reduce(function (preValue,curValue,index,array) {    return preValue + curValue;}, 5); //15
preValue curValue index array 返回值
第一次回调 5 0 0 [0,1,2,3,4] 5
第二次回调 5 1 1 [0,1,2,3,4] 6
第三次回调 6 2 2 [0,1,2,3,4] 8
第四次回调 8 3 3 [0,1,2,3,4] 11
第五次回调 11 4 4 [0,1,2,3,4] 15

这样一来,不用多说,应该都知道,可以使用 reduce() 实现数组求和的功能。如:

var arr = [1,2,3,4,5,6];Array.prototype.sum = function (){    var sumResult = 0;    return this.reduce(function (preValue, curValue) {        return sumResult = preValue + curValue;    });    return sumResult;}arr.sum(); // 21

回到文章的前面,来看看使用 reduce() 方法对数组求和,需要多少时间:

var arr = [1,2,3,4,5,6];console.time("ruduce");Array.prototype.ruduceSum = function (){    for (var i = 0; i < 10000; i++) {        return  this.reduce (function (preValue, curValue) {            return preValue + curValue;        });    }}arr.ruduceSum();console.log('最终的值:' + arr.ruduceSum()); // 21console.timeEnd("ruduce"); // 0.417ms

同时看看所费时间的对比:

循环类型 最终值(和) 所费时间
for 21 54.965ms
while 21 53.056ms
reduce 21 0.417ms

在Chrome浏览器下,每次执行的数据都会略有不同,但可以明显的看出 reduce() 对数组项求和所费时间是最短的。

reduceRight() 方法

reduceRight() 方法的功能和 reduce() 功能是一样的,不同的是 reduceRight() 从数组的末尾向前将数组中的数组项做累加。

reduceRight() 首次调用回调函数 callbackfn 时, prevValue 和 curValue 可以是两个值之一。如果调用 reduceRight() 时提供了 initialValue 参数,则 prevValue 等于 initialValue , curValue 等于数组中的最后一个值。如果没有提供 initialValue 参数,则 prevValue 等于数组最后一个值, curValue 等于数组中倒数第二个值。

来看实例:

var arr = [0,1,2,3,4];arr.reduceRight(function (preValue,curValue,index,array) {    return preValue + curValue;}); // 10

回调将会被调用四次,每次调用的参数及返回值如下:

preValue curValue index array 返回值
第一次回调 4 3 3 [0,1,2,3,4] 7
第二次回调 7 2 2 [0,1,2,3,4] 9
第三次回调 9 1 1 [0,1,2,3,4] 10
第四次回调 10 0 0 [0,1,2,3,4] 10

如果提供一个初始值 initialValue 为 5 :

var arr = [0,1,2,3,4];arr.reduceRight(function (preValue,curValue,index,array) {    return preValue + curValue;}, 5); // 15

回调将会被调用五次,每次调用的参数及返回的值如下:

preValue curValue index array 返回值
第一次回调 5 4 4 [0,1,2,3,4] 9
第二次回调 9 3 3 [0,1,2,3,4] 12
第三次回调 12 2 2 [0,1,2,3,4] 14
第四次回调 14 1 1 [0,1,2,3,4] 15
第五次回调 15 0 0 [0,1,2,3,4] 15

同样的,可以对一个数组求和,也可以使用 reduceRight() 方法:

var arr = [1,2,3,4,5,6];console.time("ruduceRight");Array.prototype.ruduceRightSum = function (){    for (var i = 0; i < 10000; i++) {        return  this.reduceRight (function (preValue, curValue) {            return preValue + curValue;        });    }}arr.ruduceRightSum();console.log('最终的值:' + arr.ruduceSum()); // 21console.timeEnd("ruduceRight"); // 5.725ms

总结

reduce() 和 reduceRight() 两个方法功能都是类似的,可以让数组调用一个回调函数 callbackfn 作为累加器。实际上根据这个回调函数,可以实现不同的功能,比如说,对数组项求合;将多个数组合并到一个数组等等。甚至配合数组其他的方法你还可以做更多功能的处理。如果感兴趣的话不仿尝试一二。

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

大漠

常用昵称“大漠”,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
How do you set the lang attribute on the  tag? Why is this important?How do you set the lang attribute on the tag? Why is this important?May 08, 2025 am 12:03 AM

Setting the lang attributes of a tag is a key step in optimizing web accessibility and SEO. 1) Set the lang attribute in the tag, such as. 2) In multilingual content, set lang attributes for different language parts, such as. 3) Use language codes that comply with ISO639-1 standards, such as "en", "fr", "zh", etc. Correctly setting the lang attribute can improve the accessibility of web pages and search engine rankings.

What is the purpose of HTML attributes?What is the purpose of HTML attributes?May 07, 2025 am 12:01 AM

HTMLattributesareessentialforenhancingwebelements'functionalityandappearance.Theyaddinformationtodefinebehavior,appearance,andinteraction,makingwebsitesinteractive,responsive,andvisuallyappealing.Attributeslikesrc,href,class,type,anddisabledtransform

How do you create a list in HTML?How do you create a list in HTML?May 06, 2025 am 12:01 AM

TocreatealistinHTML,useforunorderedlistsandfororderedlists:1)Forunorderedlists,wrapitemsinanduseforeachitem,renderingasabulletedlist.2)Fororderedlists,useandfornumberedlists,customizablewiththetypeattributefordifferentnumberingstyles.

HTML in Action: Examples of Website StructureHTML in Action: Examples of Website StructureMay 05, 2025 am 12:03 AM

HTML is used to build websites with clear structure. 1) Use tags such as, and define the website structure. 2) Examples show the structure of blogs and e-commerce websites. 3) Avoid common mistakes such as incorrect label nesting. 4) Optimize performance by reducing HTTP requests and using semantic tags.

How do you insert an image into an HTML page?How do you insert an image into an HTML page?May 04, 2025 am 12:02 AM

ToinsertanimageintoanHTMLpage,usethetagwithsrcandaltattributes.1)UsealttextforaccessibilityandSEO.2)Implementsrcsetforresponsiveimages.3)Applylazyloadingwithloading="lazy"tooptimizeperformance.4)OptimizeimagesusingtoolslikeImageOptimtoreduc

HTML's Purpose: Enabling Web Browsers to Display ContentHTML's Purpose: Enabling Web Browsers to Display ContentMay 03, 2025 am 12:03 AM

The core purpose of HTML is to enable the browser to understand and display web content. 1. HTML defines the web page structure and content through tags, such as, to, etc. 2. HTML5 enhances multimedia support and introduces and tags. 3.HTML provides form elements to support user interaction. 4. Optimizing HTML code can improve web page performance, such as reducing HTTP requests and compressing HTML.

Why are HTML tags important for web development?Why are HTML tags important for web development?May 02, 2025 am 12:03 AM

HTMLtagsareessentialforwebdevelopmentastheystructureandenhancewebpages.1)Theydefinelayout,semantics,andinteractivity.2)SemantictagsimproveaccessibilityandSEO.3)Properuseoftagscanoptimizeperformanceandensurecross-browsercompatibility.

Explain the importance of using consistent coding style for HTML tags and attributes.Explain the importance of using consistent coding style for HTML tags and attributes.May 01, 2025 am 12:01 AM

A consistent HTML encoding style is important because it improves the readability, maintainability and efficiency of the code. 1) Use lowercase tags and attributes, 2) Keep consistent indentation, 3) Select and stick to single or double quotes, 4) Avoid mixing different styles in projects, 5) Use automation tools such as Prettier or ESLint to ensure consistency in styles.

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

Video Face Swap

Video Face Swap

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

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.