示例数据
const animals = [
{
"name": "cat",
"size": "small",
"weight": 5
},
{
"name": "dog",
"size": "small",
"weight": 10
},
{
"name": "lion",
"size": "medium",
"weight": 150
},
{
"name": "elephant",
"size": "big",
"weight": 5000
}
]
map()
定义和用法:
map() 方法返回一个新数组,数组中的元素为原始数组元素调用函数处理后的值。
map() 方法按照原始数组元素顺序依次处理元素。
语法:
array.map(function(currentValue,index,arr), thisValue)
示例:获取所有动物的name
//用for循环来实现
let animal_names = [];
for (let i = 0; i < animals.length; i++) {
animal_names.push(animals[i].name);
}
//用map实现
let animal_names = animals.map((animal, index, animals) => {
return animal.name
})
filter()
定义和用法:
filter() 方法创建一个新的数组,新数组中的元素是通过检查指定数组中符合条件的所有元素。
语法:
array.filter(function(currentValue,index,arr), thisValue)
示例:获取size属性为small的动物
//用for循环来实现
let small_animals = [];
for (let i = 0; i < animals.length; i ++) {
if (animals[i].size === "small") {
small_animals.push(animals[i])
}
}
//用filter实现
let small_animals = animals.filter((animal) => {
return animal.size === "small"
})
reduce()
定义和用法:
reduce() 方法接收一个函数作为累加器,数组中的每个值(从左到右)开始缩减,最终计算为一个值。
reduce() 可以作为一个高阶函数,用于函数的 compose。
语法:
array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
示例:计算所有动物的重量之和
//用for循环来实现
let total_weight = 0;
for (let i = 0; i < animals.length; i++) {
total_weigth += animals[i].weight
}
//用reduce实现
let total_weight = animals.reduce((weight, animal, index, animals) => {
return weight += animal.weight
}, 0)
forEach()
定义和用法:
forEach() 方法用于调用数组的每个元素,并将元素传递给回调函数。
语法:
array.forEach(function(currentValue, index, arr), thisValue)
