简体   繁体   English

关于javascript中的过滤器和数组元素[0]的问题

[英]Question about filter in javascript and element [0] of array

I'm studying Javascript and I have this example using filter...我正在学习 Javascript,我有这个使用过滤器的例子......

I have an object called fruits like that...我有一个叫做水果这样的对象......

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
            }... 

I have a cart with the items of fruits.我有一辆装有水果的推车。

cart = [0, 3, 4, 5, 3]

this is the part that I don't understand...这是我不明白的部分......

const getCostOf = id => (data.fruits.filter(item => item.id == id))[0].price

What are doing在做什么

[0].price

??? ??? Why I have to get the element [0] if item is going to change every step...如果项目要更改每一步,为什么我必须获取元素 [0]...

If I have other function...如果我有其他功能...

const getTotal = cart => {
  let total = 0;
  cart.map(item => total += getCostOf(item))
  return total;
}

Why in getConstOf为什么在getConstOf

The example is using [0].price and not [item].price ?该示例使用[0].price而不是[item].price

You said you had a variable data which is an array.你说你有一个变量数据,它是一个数组。 But from your example that looks like your variable data is in fact an object and not an array.但是从您的示例来看,您的变量数据实际上是一个对象而不是数组。 And the filter method can only used for array's and not for object.而 filter 方法只能用于数组,不能用于对象。

So what you need to do in order to make the filter method to start filtering is to pierce into your object and grab the "fruits" key as it the array in your example and you can do it like this:因此,为了使 filter 方法开始过滤,您需要做的是刺入您的对象并获取“fruits”键作为您示例中的数组,您可以这样做:

data.fruits then you can filter those objects inside the array of fruits. data.fruits然后您可以过滤水果数组中的这些对象。 ie IE

const getCostOf = id => data.fruits.filter(item => item.id == id))[0].price

As for your [0].price without it, you will have a return of the array of object that your id parameter matches with the item.id .至于没有它的[0].price ,您将返回id参数与item.id匹配的对象数组。 So [0] you are saying you want the first element in the array to be returned.所以 [0] 你是说你想要返回数组中的第一个元素。 And now you are returning the object from the array.现在您正在从数组中返回对象。 then pinpoint further you wanted the price so .price will give you the price.然后进一步查明您想要的价格,因此.price会给您价格。

So at the end in example id = 3 then the price would be 45 from your result因此,在示例 id = 3 的最后,您的结果中的价格将为 45

const getCostOf = id => data.fruits.filter(item => item.id === id)[0].price

console.log(getCostOf(3))

filter() returns an array with all items that match the given criteria. filter()返回一个数组,其中包含与给定条件匹配的所有项目。 In this case item => item.id == id so all items that match the provided id .在这种情况下item => item.id == id所以所有与提供的id匹配的项目。 The [0] after it takes the first matching element and .price will then give you the price of the matching item. [0]后面的第一个匹配元素和.price将为您提供匹配项目的价格。

However if you have a lot of products a better option for finding the first product is find() .但是,如果您有很多产品,找到第一个产品的更好选择是find() Which iterates until it finds a match and directly returns it instead of trying to find all matches.迭代直到找到匹配项并直接返回它而不是尝试查找所有匹配项。

const getCostOf = id => data.fruits.find(item => item.id == id).price;

Or if you call getCostOf() often you might want to prepare the data structure and index the items based on id in a Map .或者,如果您经常调用getCostOf()您可能想要准备数据结构并根据Map id索引项目。 This does introduce some overhead, but will pay off if you often need to lookup items.这确实会带来一些开销,但如果您经常需要查找项目,这将是值得的。

const fruits = new Map(data.fruits.map(item => [item.id, item]));
const getCostOf = id => fruits.get(id).price;

This last solution assumes the ids are unique.最后一个解决方案假设 ID 是唯一的。 If they are not, later versions of an item with the same id will override earlier defined versions.如果不是,具有相同 id 的项目的更高版本将覆盖早期定义的版本。 Resulting in the last item returned instead of the first one.导致返回最后一个项目而不是第一个项目。 You also need to update fruits if data.fruits is replaced or items are added/removed from the array.如果data.fruits被替换或从数组中添加/删除项目,您还需要更新fruits

data.fruits.filter(item => item.id == id) creates an array with just one product, the one with the id given in the parameter. data.fruits.filter(item => item.id == id)创建一个只有一种产品的数组,该数组具有参数中给出的id Accessing this array with [0] will get the one product in the array and .price will return its price使用[0]访问此数组将获得数组中的一个产品,而.price将返回其价格

因为filter()函数返回一个包含所需产品的数组,而价格是该产品的价格属性。

const getCostOf = id => (data.fruits.filter(item => item.id == id))[0].price

This code can be written as这段代码可以写成

 const getCostOf = id => { 
let fruits  = data.fruits.filter(item => item.id == id)) // filter will array return an array;
let fruit  = fruits[0]; // selecting first match
return fruit.price;
}

A better way to write it will be to use find since find only returns first match not array.编写它的更好方法是使用 find,因为 find 只返回第一个匹配而不是数组。

 const getCostOf = id => data.fruits.find(item => item.id == id).price

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM