亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用函數和 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 關注
  • 185 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號