【问题标题】:Array of objects with conditonal有条件的对象数组
【发布时间】:2023-04-09 11:15:01
【问题描述】:

所以我试图返回在此函数中查找的商品的价格:

如果项目不在列表中怎么办? 如果不是,我需要返回

“没有找到同名的项目”

我该怎么做呢?

let items = [{
    itemName: "Effective Programming Habits",
    type: "book",
    price: 13.99
  },
  {
    itemName: "Creation 3005",
    type: "computer",
    price: 299.99
  },
  {
    itemName: "Finding Your Center",
    type: "book",
    price: 15.00
  }
]

function priceLookup(array, item) {
  let results = 0;
  for (let i = 0; i < array.length; i++) {
    if (array[i].itemName === item) {
      results = array[i].price
    }
  }
  return results;
}

【问题讨论】:

  • 如果项目不在列表中,那么你将不会得到任何你会得到 0 的东西。另外我建议你看看 Array.reduce 方法
  • 或查看Array.filter
  • results 初始化为null,因为 0 在理论上是一个有效的价格值。然后检查结果是否为空 - 没有找到

标签: javascript arrays for-loop object if-statement


【解决方案1】:

我会简单地重写你的查找函数如下:

function priceLookup(array, item) {
  for (let i = 0; i < array.length; i++) {
    if (array[i].itemName === item) {
      return array[i].price
    }
  }
  return "No item found with that name";
}

【讨论】:

    【解决方案2】:

    您可以在这里实现不同的逻辑,如下所示:

    • 不要返回默认值为 0 的 price,而是将其设置为 null
    • 案例 #1: 找到商品,然后从数组中返回实际价格。
    • 案例 #2: 未找到商品,然后将价格返回为 null,然后您可以简单地检查并设置默认值,例如:

      priceLookup(items, "abc") || "No item found with that name"
      

    let items = [{itemName:"Effective Programming Habits",type:"book",price:13.99},{itemName:"Creation 3005",type:"computer",price:299.99},{itemName:"Finding Your Center",type:"book",price:15}];
    
    function priceLookup(array, item) {
      let results = null;
      var foundItem = array.find(a => a.itemName === item);
      if (foundItem)
        results = foundItem.price;
      return results;
    }
    
    console.log( priceLookup(items, "Creation 3005") )
    console.log( priceLookup(items, "abc") || "No item found with that name" )

    或者,您也可以用更少的代码简单地做到这一点:

    let items = [{itemName:"Effective Programming Habits",type:"book",price:13.99},{itemName:"Creation 3005",type:"computer",price:299.99},{itemName:"Finding Your Center",type:"book",price:15}];
    
    function priceLookup(array, item) {
      return (array.find(a => a.itemName === item) || {}).price;
    }
    
    console.log( priceLookup(items, "Creation 3005") )
    console.log( priceLookup(items, "abc") || "No item found with that name" )

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-06-06
      • 1970-01-01
      • 2020-08-28
      • 2021-12-26
      • 2019-06-28
      • 1970-01-01
      • 2021-12-05
      • 1970-01-01
      相关资源
      最近更新 更多