var array = ['a', 'b', 'c'];
array.forEach(function(el) {
console.log(el);
});
array.forEach((el) => {
console.log(el);
});
// 输出为:a,b,c
var arr = [1,2,3,4];
arr.forEach(alert);
// 等价于:
var arr = [1, 2, 3, 4];
for (var k = 0, length = arr.length; k < length; k++) {
alert(arr[k]);
}
var arr = [2, 3, 7];
for(var i=0; i < arr.length; i++) {
console.log('a['+i+'] = '+ arr[i]);
}
// a[0] = 2
// a[1] = 3
// a[2] = 7
// 等价于:
arr.forEach(function(v, i){
console.log('a['+i+'] = '+ v);
})
var arr = [1,2,3,4];
var sum = 0;
arr.forEach(function(value,index,array){
array[index] === value; //结果为true
sum += value;
});
console.log(sum); //结果为 10
var words = ['one', 'two', 'three', 'four'];
words.forEach(function(word) {
console.log(word);
if (word === 'two') {
words.shift();
}
});
// one
// two
// four
function flatten(arr) {
const result = [];
arr.forEach((i) => {
if (Array.isArray(i))
result.push(...flatten(i));
else
result.push(i);
})
return result;
}
// Usage
const problem = [1, 2, 3, [4, 5, [6, 7], 8, 9]];
flatten(problem); // [1, 2, 3, 4, 5, 6, 7, 8, 9]
// 输出12456,3不会输出
[1,2,3,4,5,6].forEach((n) => {
if (n=== 3) {
return
}
console.log(n)
})
// 输出12,3456不会输出
try{
[1,2,3,4,5,6].forEach((n) => {
if (n=== 3) {
throw new Error('End Loop')
}
console.log(n)
})
} catch (e) {}
此页面不支持夜间模式!
已进入夜间模式!
已进入普通模式!
搜索框不允许为空
签到成功!经验+5!芋圆币+2!
签到失败!今日已签到!
需要登录社区账号才可以进入!