语法:1
array.forEach(callback(currentValue, index, array){
//do something
}, this)
array.forEach(callback[, thisArg])
参数
callback为数组中每个元素执行的函数,该函数接收三个参数:currentValue数组中正在处理的当前元素。
index可选
数组中正在处理的当前元素的索引。
array可选
forEach()方法正在操作的数组。
thisArg可选
可选参数。当执行回调 函数时用作this的值(参考对象)。
返回值
undefined.
例如:
var array = ['1111', '2222', '3333', '4444'];
array.forEach(function(item, index, array) {
console.log(item);
console.log(index);
console.log(array);
})
output:
> "1111"
> 0
> Array ["1111", "2222", "3333", "4444"]
> "2222"
> 1
> Array ["1111", "2222", "3333", "4444"]
> "3333"
> 2
> Array ["1111", "2222", "3333", "4444"]
> "4444"
> 3
> Array ["1111", "2222", "3333", "4444"]
下面是json格式的用法
嗯,正确的声明是var,我这里使用的是let,是因为我使用这个用例是微信小程序的用例。所以才这样声明。
let products = [
{ product: "书包", cost: 60 },
{ product: "巧克力", cost: 8 },
{ product: "铅笔", cost: 2 },
{ product: "耳机", cost: 199 }
];
products.forEach(function(item) {
console.log(item.product + "的价格是" + item.cost + "元");
});
书包的价格是60元
巧克力的价格是8元
铅笔的价格是2元
耳机的价格是199元
价格大于10的
let products = [
{ product: "书包", cost: 60 },
{ product: "巧克力", cost: 8 },
{ product: "铅笔", cost: 2 },
{ product: "耳机", cost: 199 }
];
products.forEach(function(item) {
if (item.cost >= 10)
console.log(item.product + "的价格是" + item.cost + "元");
});
书包的价格是60元
耳机的价格是199元
嗯,,,看来是得补一下JavaScript了,要不然写小程序都不好写。

本文详细介绍了 JavaScript 中的 forEach 方法的语法、参数及返回值,并通过具体示例展示了如何使用此方法遍历数组元素,包括基本的元素遍历和条件筛选应用。
673

被折叠的 条评论
为什么被折叠?



