为了账号安全,请及时绑定邮箱和手机立即绑定

使用函数和 for 循环时,如果存在重复值或相似值,如何返回对象中的第一个匹配值?

使用函数和 for 循环时,如果存在重复值或相似值,如何返回对象中的第一个匹配值?

弑天下 2023-03-24 16:23:38
例如,假设我的数据集中有以下重复项,并且我将其name = Finding Your Center作为参数输入到以下函数中。我想返回price第一个匹配的itemName。上面的函数不会返回 15.00,因为 15.00 是与字符串参数匹配的第一个值,而是返回 1500,因为它循环遍历整个对象数据,而不是在第一个匹配/相似值处停止。 let duplicates = [      {        itemName: "Finding Your Center",        type: "book",        price: 15.00      },      {        itemName: "Finding Your Center",        type: "book",        price: 1500.00      }];到目前为止,这是我的伪代码和函数。此函数返回我使用特定数据集所需的所有值。// Create priceLookUp function to find price of a single item// Give the function two paramenters: an array of items and an item name as string// priceLookUp = undefined for nomatching name// loop through the items array checking if name = itemName// return the price of item name matching string// for a matching/similar value the code should stop running at the first value instead of going through the rest of the loopfunction priceLookup (items, name){  let priceOfItem = undefined;  for (let i = 0; i < items.length; i++)   if (name === items[i].itemName)   {priceOfItem = items[i].price;}  return priceOfItem;}我将如何获得使用 for 循环编写的函数以在第一个匹配值处停止运行而不循环遍历整个数组?
查看完整描述

4 回答

?
暮色呼如

TA贡献1853条经验 获得超9个赞

只需删除变量并返回匹配。


function priceLookup (items, name) {

  for (let i = 0; i < items.length; i++) {

    if (name === items[i].itemName) return items[i].price;

  }

}


查看完整回答
反对 回复 2023-03-24
?
叮当猫咪

TA贡献1776条经验 获得超12个赞

function priceLookup (items, search) {

  let priceOfItem = [];

  for (let i = 0; i < items.length; i++) 

  if (search === items[i].itemName)

    {priceOfItem.push(items[i].price);}

    return priceOfItem[0];

 }

  


对于这个函数,创建一个空数组来保存新的返回值对我来说更有意义。由于我们只想返回第一个匹配项,因此返回数组中的第一个值是有意义的。通过返回 priceOfItem[0],如果有多个值满足 if 条件,它会返回数组中的第一个值。


查看完整回答
反对 回复 2023-03-24
?
阿波罗的战车

TA贡献1862条经验 获得超6个赞

在你的 if 中使用break语句。您还可以使用find数组中存在的方法。



查看完整回答
反对 回复 2023-03-24
?
MYYA

TA贡献1868条经验 获得超4个赞

您需要重写您的函数以在第一次匹配时停止,因为您可以使用 'break' 关键字,如下所示:


function priceLookup (items, name){

  let priceOfItem = undefined;

  for (let i = 0; i < items.length; i++) {

      if (name === items[i].itemName) {

          priceOfItem = items[i].price;

          break;

      }

  }

  return priceOfItem;

}


查看完整回答
反对 回复 2023-03-24
  • 4 回答
  • 0 关注
  • 126 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信