百分百源码网-让建站变得如此简单! 登录 注册 签到领金币!

主页 | 如何升级VIP | TAG标签

当前位置: 主页>网站教程>JS教程> 总结javascript中遍历数组的几种办法
分享文章到:

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

发布时间:09/01 来源:未知 浏览: 关键词:

本篇文章给大家总结了一些javascript遍历数组的几种办法。有必然的参照 价值,有需要的伴侣可以参照 一下,但愿对大家有所帮忙。

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

while轮回

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

while (index < array.length) {
    console.log(array[index]);
    index++;
}

在这里插入图片描述

for轮回

const array = [1,2,3,4,5];
for(let index=0;index<array.length;index++){
    console.log(array[index]);
}
for(let index in array){
    console.log(array[index]);
}

在这里插入图片描述

forEach

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<6;
if(array.every(under_six)){
    console.log(`every elemnet in the array is less than 6`);
}
else{
    console.log(`at least one element in the array was bigger than 6`);
}

在这里插入图片描述

some

测试可否至少有一个元素与布尔函数匹配

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视频教程

以上就是总结javascript中遍历数组的几种办法的具体内容,更多请关注百分百源码网其它相关文章!

打赏

打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,你说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

百分百源码网 建议打赏1~10元,土豪随意,感谢您的阅读!

共有151人阅读,期待你的评论!发表评论
昵称: 网址: 验证码: 点击我更换图片
最新评论

本文标签

广告赞助

能出一分力是一分吧!

订阅获得更多模板

本文标签

广告赞助

订阅获得更多模板