AI编程助手
AI免费问答

总结javascript中遍历数组的几种方法

青灯夜游   2020-07-29 16:58   3439浏览 转载
本篇文章给大家总结了一些javascript遍历数组的几种方法。有一定的参考价值,有需要的朋友可以参考一下,希望对大家有所帮助。

有几种方法可以遍历数组,下面将逐个罗列!

while循环

let index = 0;
const array = [1, 2, 3, 4, 5];

while (index <p><img src="https://img.php.cn/upload/article/000/000/024/bcc572aa622abdd75b7629dbc11ff12c-0.png?x-oss-process=image/resize,p_40" alt="在这里插入图片描述"></p><h2>for循环</h2><pre class="brush:js;toolbar:false;">const array = [1,2,3,4,5];
for(let index=0;index<array.length for><p><img src="https://img.php.cn/upload/article/000/000/024/bcc572aa622abdd75b7629dbc11ff12c-1.png?x-oss-process=image/resize,p_40" alt="在这里插入图片描述"></p>
<h2>forEach</h2>
<pre class="brush:js;toolbar:false;">const array=[1,2,3,4,5];
array.forEach(function(current_value,index,array){
    console.log(`At index ${index} in array ${array} the value is ${current_value}`)
})

在这里插入图片描述

map

最后一个构造很有用,但是不会返回新数组,这对于你的特定情况可能是不希望的。map通过对每个元素应用一个函数然后返回新数组来解决此问题。

const array = [1,2,3,4,5];
const square = x =>Math.pow(x,2);
const squares = array.map(square);
console.log(`${array}`);
console.log(`${squares}`)

在这里插入图片描述

reduce

reduce()方法对累加器和数组中的每个元素(从左到右)应用一个函数,以将其减小为单个值

const array = [1,2,3,4,5];
const sum = (x,y) => x + y;

const array_sum = array.reduce(sum,0);
console.log(`the sum of arrray:${array} is ${array_sum}`);

在这里插入图片描述

filter

根据布尔函数过滤筛选数组中的元素

const array = [1,2,3,4,5];
const even = x => x%2 === 0;
const even_array = array.filter(even);
console.log(`even numbers in array ${array} : ${even_array}`);

在这里插入图片描述

every

得到了一个数组,想测试每个元素是否满足给定条件

const array = [1,2,3,4,5,8];
const under_six = x => x<p><img src="https://img.php.cn/upload/article/000/000/024/2c29c6f0b82e1715a594aee42b26c693-6.png?x-oss-process=image/resize,p_40" alt="在这里插入图片描述"></p><h2>some</h2><p>测试是否至少有一个元素与布尔函数匹配</p><pre class="brush:js;toolbar:false;">const array = [2,4,5,6,8];
const over_five = x => x>5;

if(array.some(over_five)){
    console.log(`at least one element bigger than 5 was found`);
}
else{
    console.log(`no element bigger than 5 was found`);
}

在这里插入图片描述

到此就结束啦,如果还有其他的欢迎补充!

相关教程推荐:JavaScript视频教程

Java免费学习笔记:立即学习
解锁 Java 大师之旅:从入门到精通的终极指南

声明:本文转载于:csdn,如有侵犯,请联系admin@php.cn删除