温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

javascript中遍历数组有哪几种方法

发布时间:2020-07-30 10:19:56 来源:亿速云 阅读:141 作者:Leah 栏目:web开发

javascript中遍历数组有哪几种方法?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。


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

while循环

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

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

javascript中遍历数组有哪几种方法

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]);
}

javascript中遍历数组有哪几种方法

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}`)
})

javascript中遍历数组有哪几种方法

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}`)

javascript中遍历数组有哪几种方法

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}`);

javascript中遍历数组有哪几种方法

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}`);

javascript中遍历数组有哪几种方法

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`);
}

javascript中遍历数组有哪几种方法

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中遍历数组有哪几种方法的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注亿速云行业资讯频道,感谢各位的阅读!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI