【问题标题】:Question about filter in javascript and element [0] of array关于javascript中的过滤器和数组元素[0]的问题
【发布时间】: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


【解决方案1】:

您说您有一个可变数据,它是一个数组。但是从您的示例来看,您的变量数据实际上是一个对象而不是一个数组。而且filter方法只能用于数组,不能用于对象。

因此,为了使过滤器方法开始过滤,您需要做的是刺入您的对象并抓住“水果”键,因为它是您示例中的数组,您可以这样做:

data.fruits 然后你可以过滤水果数组中的那些对象。即

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

至于您的[0].price 没有它,您将返回您的id 参数与item.id 匹配的对象数组。所以 [0] 你说你想要返回数组中的第一个元素。现在您正在从数组中返回对象。然后进一步确定您想要的价格,以便.price 会给您价格。

因此,在示例 id = 3 的最后,您的结果中的价格将为 45

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

console.log(getCostOf(3))

【讨论】:

    【解决方案2】:

    filter() 返回一个包含所有符合给定条件的项目的数组。在本例中为item => item.id == id,因此所有与提供的id 匹配的项目。 [0] 在它获取第一个匹配元素之后,.price 将为您提供匹配项目的价格。

    但是,如果您有很多产品,查找第一个产品的更好选择是find()。它会迭代直到找到匹配项并直接返回它,而不是尝试查找所有匹配项。

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

    或者,如果您经常调用getCostOf(),您可能想要准备数据结构并根据idMap 中索引项目。这确实会带来一些开销,但如果您经常需要查找项目,就会得到回报。

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

    最后一个解决方案假定 id 是唯一的。如果不是,则具有相同 id 的项目的更高版本将覆盖早期定义的版本。导致返回的最后一项而不是第一项。如果 data.fruits 被替换或从数组中添加/删除项目,您还需要更新 fruits

    【讨论】:

    • 如果你仔细看他的例子,他的数据变量实际上是一个对象而不是一个数组。所以filterfind 方法都不起作用。
    • @Mohamed 这是一个细节。 OP 应该提供一个一致的例子。我基于 OPs getCostOf 定义的这个答案,而不是 data 结构。这个答案试图解释一个概念,将data 更改为data.fruits 很容易。
    【解决方案3】:

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

    【讨论】:

      【解决方案4】:
      const getCostOf = id => (data.fruits.filter(item => item.id == id))[0].price
      

      这段代码可以写成

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

      更好的编写方法是使用 find,因为 find 只返回第一个匹配项而不是数组。

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

      【讨论】:

      • 如果你仔细看他的例子,他的数据变量实际上是一个对象而不是一个数组。所以filterfind 方法都不起作用。
      【解决方案5】:

      data.fruits.filter(item => item.id == id) 创建一个只有一个产品的数组,即参数中给出的id。 使用[0] 访问此数组将获得数组中的一个产品,.price 将返回其价格

      【讨论】:

      • 如果你仔细看他的例子,他的数据变量实际上是一个对象而不是一个数组。所以filterfind 方法都不起作用。
      • 啊是的我忘了写水果
      猜你喜欢
      • 2019-05-25
      • 1970-01-01
      • 2011-02-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-15
      • 1970-01-01
      • 2016-09-19
      相关资源
      最近更新 更多