forEach() 方法小记

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Magic_Ninja/article/details/85331875

语法: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 ↩︎

猜你喜欢

转载自blog.csdn.net/Magic_Ninja/article/details/85331875