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

Javascript 使用函数和for循环时,如果存在重复值或类似值,如何返回对象中的第一个匹配值?,javascript,arrays,function,object,return,Javascript,Arrays,Function,Object,Return,例如,假设我的数据集中有以下重复项,我将name=Finding Your Center作为参数输入到下面的函数中。我想返回第一个匹配的itemName的price。因为15.00是与字符串参数匹配的第一个值,所以上面的函数不会返回15.00,而是返回1500,因为它在整个对象数据中循环,而不是在第一个匹配/类似的值处停止 let duplicates = [ { itemName: "Finding Your Center",

例如,假设我的数据集中有以下重复项,我将
name=Finding Your Center
作为参数输入到下面的函数中。我想返回第一个匹配的
itemName
price
。因为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 loop

function 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;
}
//创建priceLookUp函数以查找单个项目的价格
//为函数指定两个参数:项数组和项名称作为字符串
//priceLookUp=未定义不匹配的名称
//循环遍历items数组,检查name=itemName
//返回商品名称匹配字符串的价格
//对于匹配/相似的值,代码应该在第一个值处停止运行,而不是遍历循环的其余部分
函数priceLookup(项目、名称){
让priceOfItem=未定义;
for(设i=0;i

如何使用for循环使函数在第一个匹配值处停止运行而不在整个数组中循环?

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

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

函数价格查找(项目、名称){
让priceOfItem=未定义;
for(设i=0;i}
只需删除变量并返回匹配即可

function priceLookup (items, name) {
  for (let i = 0; i < items.length; i++) {
    if (name === items[i].itemName) return items[i].price;
  }
}
函数价格查找(项目、名称){
for(设i=0;i
函数价格查找(项目,搜索){
让priceOfItem=[];
for(设i=0;i
只需更改
priceOfItem=items[i]。价格
退货项目[i]。价格
如果在
for
中没有
{}
,则它只将一条语句视为它的块。仅当
语句被视为
块的
的一部分时,才是
,而不是
返回
。您可以在for循环中添加
{}
:for(…){if(…){…}返回priceOfItem}
@Nick,如果您声明
priceOfItem=items[i]。price
在for循环之前,这将成为一个全局值,并且
i
本身将是未定义的。这只是另一个你必须定义的变量,使函数更复杂。另外,返回
项[i]。如果恰好有多个键值对与if条件匹配,price
仍然不会阻止函数返回多个数组值。@ElinaMcGill我在
for
循环之前没有说过,我说的是替换
for
循环中的代码。
for
循环中的
return
将立即终止函数,使其仅返回第一个匹配项(如果有)。