js中forEach是用于遍历数组的方法,将遍历到的元素传递给回调函数,遍历的数组不能是空的要有值
forEach 语法:
// 箭头函数
[].forEach(value => {
/* … */ })
[].forEach((value , index) => {
/* … */ })
[].forEach((value , index, array) => {
/* … */ })
// 回调函数
[].forEach(callbackFn)
// 内联回调函数
[].forEach(function(value ) {
/* … */ })
[].forEach(function(value , index) {
/* … */ })
[].forEach(function(value , index, array){
/* … */ })
// value : 必须,当前元素的值
// index : 可选,当前元素的索引
// array : 可选,当前数组对象
var array = ['a', 'b', 'c'];
array.forEach(function(value) {
console.log(value);
});
forEach不支持break与continue
let arr = [1, 2, 3, 4]
arr.forEach((self,index) => {
console.log(self);
if (self === 2) {
break; //报错
};
});
arr.forEach((self,index) => {
console.log(self);
if (self === 2) {
continue; //报错
};
});