创建一个函数 findItems

create a function findItems

我已经学习 Javascript 几周了(主要是数组、函数、for 循环和 if 语句)。我遇到了一个困扰我的问题,非常感谢任何形式的洞察力或对问题的分解。

问题是:

Create a function findItems that
•   takes in two arguments: an array of items, and a type of item as a string
•   returns an array of items that have a type that matches the type passed in

使用下面的示例数据, findItems(items, "book") /* =>

[{ 
    itemName: "Effective Programming Habits", 
    type: "book", 
    price: 18.99
}]
  */

注意:在您编写此函数并通过第一组测试后,第二组测试将出现在第 2 部分。 第 2 部分 - 查找项目,扩展

Add the following features to your findItems function:
    •   If there are no items in the cart array, return the string "Your cart does not have any items in it."
    •   If there are no items that match the given type, return the string "No items found of that type. Please search for a different item.".
Sample Shopping Cart Data

let items = [
  { 
    itemName: "Effective Programming Habits", 
    type: "book", 
    price: 18.99
  },
  {
    itemName: "Creation 3005", 
    type: "computer",
    price: 399.99
  },
  {
    itemName: "Orangebook Pro", 
    type: "computer",
    price: 899.99
  }
];

有大神知道怎么解决吗?或者能提供一下细目吗?

您应该遍历给定的数组,然后将具有 type 字段的任何对象添加到临时数组,然后 return 数组。像这样:

function findItems(arr, type) {
    let temp = [];
    for (let i = 0; i < arr.length; i++) {
        const item = arr[i];
        if (item.type === type) {
            temp.push(item);
        }
    }
    return temp;
}