JS遍历的方式
程序员文章站
2022-06-16 12:06:26
...
JS遍历的几种方式
1.普通方式
1.1 for循环
<script>
let arrayStr = ['111', '222', '333', '444', '555'];
for (let i = 0; i < arrayStr.length; i++){
console.log(i + ':' + arrayStr[i]);
}
</script>
1.2 for in
<script>
let arrayStr = ['111', '222', '333', '444', '555'];
for (let i in arrayStr){
console.log(i + ':' + arrayStr[i]);
}
</script>
1.3 for of
<script>
let arrayStr = ['111', '222', '333', '444', '555'];
for (let item of arrayStr){
console.log(item);
}
</script>
1.4 forEach
<script>
let arrayStr = ['111', '222', '333', '444', '555'];
arrayStr.forEach((item, index, array)=>{
console.log('当前对象:' + item);
console.log('当前索引:' + index);
console.log('原始数组:' + array);
})
</script>
2.高阶方式
2.1 filter
filter 不改变原来的数组
<script>
let arrayNum = [111, 222, 333, 444, 555];
// filter中的回调函数中有一个要求:必须返回一个boolean值
/*true: 当返回为true, 函数内部,自动将这次回调的的年加入到你的新数组中,
fasle:当放回为false,函数内部回过滤掉这次的n*/
const newArrayNum = arrayNum.filter((item, index, array) => {
console.log("当前对象:" + item);
console.log("当前索引:" + index);
console.log("原数组:" + array);
return item > 222;
});
console.log("原数组:" + arrayNum);
console.log("filter之后的数组:" + newArrayNum);
</script>
2.2 map循环
修改数组中的值
<script>
let arrayNum = [111, 222, 333, 444, 555];
// 将新的元素插入到当前的index并返回新的数组
const newArrayNum = arrayNum.map((item, index, array) => {
console.log("当前对象:" + item);
console.log("当前索引:" + index);
console.log("原数组:" + array);
return item * 10;
});
console.log("原数组:" + arrayNum);
console.log("map之后的数组:" + newArrayNum);
</script>
2.3 reduce
累加器:对数组中所有内容进行汇总
<script>
let arrayNum = [111, 222, 333, 444, 555];
//
const newArrayNum = arrayNum.reduce((previous, currentValue, currentIdex, array) => {
console.log("累加的前一个值:" + previous);
console.log("当前对象:" + currentValue);
console.log("当前索引:" + currentIdex);
console.log("原数组:" + array);
return previous + currentValue;
});
console.log('=======================');
console.log("原数组:" + arrayNum);
console.log("总和:" + newArrayNum);
</script>