forEach() 方法小记

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

语法: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了,要不然写小程序都不好写。


  1. 语法、参数、返回值,来自:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach ↩︎

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

之芫

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值