如何遍历数组?

博客介绍了JavaScript中的循环和数组方法,包括while循环、for循环,以及数组的forEach、map、reduce、filter、every、some等方法,这些都是前端开发中常用的编程技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.while

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

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

2.for ()

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

3.forEach

const array = [1,2,3,4,5,6];

array.forEach(function(current_value, index, array) {
  console.log(`在数组下标 ${index} 处数组 ${array} 的值是 ${current_value}`);
});
// => undefined

4.map

const array = [1,2,3,4,5,6];
const square = x => Math.pow(x, 2);
const squares = array.map(square);
console.log(`原始数组: ${array}`);
console.log(`平方后的数组: ${squares}`);

5.reduce

const array = [1,2,3,4,5,6];
const sum = (x, y) => x + y;
const array_sum = array.reduce(sum, 0);
console.log(`数组 ${array} 加起来的和是: ${array_sum}`);

6.filter

const array = [1,2,3,4,5,6];
const even = x => x % 2 === 0;
const even_array = array.filter(even);
console.log(`数组 ${array} 中的偶数是: ${even_array}`);

7.every

const array = [1,2,3,9,5,6];
const under_seven = x => x < 7;

if (array.every(under_seven)) {
  console.log('数组中每个元素都小于7');
} else {
  console.log('数组中至少有一个元素大于7');
}

8.some

const array = [1,2,3,7,5,6,4];
const over_seven = x => x > 7;

if (array.some(over_seven)) {
  console.log('至少有一个元素大于7');
} else {
  console.log('没有元素大于7');
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值