本篇讲的是四种数组遍历的方法;需要在<script></script>标签内输入。
首先在script里面定义一个数组
let array=[30,50,35,69,100]
方法一 : index(下标:从0开始)
for(let index=0;index<array.length;index++){
document.write(array[index]+":hello<br>");
}
运行结果如图:
方法二: index(下标:从0开始)
for(let index in array){
document.write(array[index]+":hello<br>");
}
运行结果如图:
方法三 : item:每一个元素
for(let item of array){
document.write(item+":hello<br>");
}
运行结果如图:
方法四 :
没有返回值
item:每一个元素
index:下标
self:函数本身
以上三个参数为形参,可以自定义命名
array.forEach(function(item,index,self){
// array.forEach(function(item){
console.log(index,item,self);
})
运行结果如图: