【发布时间】:2021-10-15 16:43:04
【问题描述】:
我正在学习 Javascript,我有这个使用过滤器的例子......
我有一个像这样叫水果的对象......
let data = {
"fruits": [{
"id": 0,
"name": "plum",
"description": "A plum is a purple fruit.",
"image": "https://cdn.shopify.com/s/files/1/0610/2881/products/cherries.jpg?v=1446676415",
"price": 220
},
{
"id": 1,
"name": "Apple",
"description": "An apple is a sweet, edible fruit produced by an apple tree. Apple trees are cultivated worldwide and are the most widely grown species in the genus Malus.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/1/15/Red_Apple.jpg/265px-Red_Apple.jpg",
"price": 35
},
{
"id": 2,
"name": "Banana",
"description": "A banana is an edible fruit – botanically a berry – produced by several kinds of large herbaceous flowering plants in the genus Musa. In some countries, bananas used for cooking may be called plantains, distinguishing them from dessert banana",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/4/44/Bananas_white_background_DS.jpg/320px-Bananas_white_background_DS.jpg",
"price": 12
},
{
"id": 3,
"name": "Grapes",
"description": "A small bunched fruit used to make wine",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/b/bb/Table_grapes_on_white.jpg/320px-Table_grapes_on_white.jpg",
"weight": 0.1,
"price": 45
}...
我有一辆装有水果的购物车。
cart = [0, 3, 4, 5, 3]
这是我不明白的部分......
const getCostOf = id => (data.fruits.filter(item => item.id == id))[0].price
在做什么
[0].price
??? 为什么我必须得到元素 [0] 如果项目要改变每一步...
如果我有其他功能...
const getTotal = cart => {
let total = 0;
cart.map(item => total += getCostOf(item))
return total;
}
为什么在getConstOf
示例使用的是[0].price 而不是[item].price?
【问题讨论】:
-
getCostOf方法将始终返回一个包含 1 个元素的数组,假设它提供了有效的 id。您可以使用[index_number]访问数组索引,因此0始终存在,因此可以安全地立即调用它。filter方法将始终保留返回true的项目。 -
您的过滤方法将不起作用,因为您的数据变量不是数组而是对象。您需要先按下
fruits键才能使用不同的 Array.prototypes。例如以data.fruits开头,然后你可以过滤.. data.fruits.filter(item => item)
标签: javascript arrays filter