js如何遍历一个数组
可以使用for循环、forEach()方法、for...of循环、map()方法等方式来遍历一个数组。
- for循环:
var arr = [1, 2, 3, 4, 5];
for(var i = 0; i < arr.length; i++){
console.log(arr[i]);
}
- forEach()方法:
var arr = [1, 2, 3, 4, 5];
arr.forEach(function(item){
console.log(item);
});
- for...of循环:
var arr = [1, 2, 3, 4, 5];
for(var item of arr){
console.log(item);
}
- map()方法:
var arr = [1, 2, 3, 4, 5];
arr.map(function(item){
console.log(item);
});
以上四种方式都可以遍历一个数组,根据实际情况选择合适的方式即可
原文地址: https://www.cveoy.top/t/topic/eN21 著作权归作者所有。请勿转载和采集!