返回一个object.keys并将其与JavaScript

时间:2016-06-25 20:39:29

标签: javascript object conditional

我在下面的代码中遇到了问题,但我无法弄清楚为什么我的测试没有通过..

例如,如果我通过canIGet('MacBook Air', 100);,则必须返回false,而是返回true

var canIGet = function(item, money) {
  itemPrices = {
   'MacBook Air': 999,
   'MacBook Pro': 1299,
   'Mac Pro': 2499,
   'Apple Sticker': 1  
  }

  if (itemPrices["MacBook Air"] >= money) {
    console.log(itemPrices["MacBook Air"], item, money);
    return true;
  } else if (itemPrices["MacBook Pro"] >= money)  {
    return true;
  } else if (itemPrices["Mac Pro"] >= money) {
    return true;
  } else if (itemPrices["Apple Sticker"] >= money) {
    return true;
  }  else {
    return false;
  }
};

我的问题是,我应该做点什么:

...
if (itemPrices.MacBookAir == item && itemPrices["MacBook Air"] >= money) {} ...

我想比较项目通行证与itemPrices'内的钥匙相同。对象

JsBin link;最后一个功能位于底部。

3 个答案:

答案 0 :(得分:2)

在if语句中,您将手动与itemPrices中的每个键进行比较。没有必要这样做 - 您已经将正确的密钥作为变量(item)传递给函数。您可以使用该变量来获取对象中的正确密钥:itemPrices[item]。现在您知道了用户要求的商品的价格。然后,您只需将其与price变量进行比较。

所以你可以摆脱所有这些if语句并用以下内容替换它们:

return itemPrices[item] <= money;

答案 1 :(得分:1)

如果你只是想看看你是否可以负担itemPrices对象中的一个产品,那么也许你应该这样做:

function canIGet(item, money) {
  itemPrices = {
   'MacBook Air': 999,
   'MacBook Pro': 1299,
   'Mac Pro': 2499,
   'Apple Sticker': 1  
  }
  // if we match an item in the prices object and the passed in 
  // money value is greater or equal to the price, then return true
  // otherwise return false
  return itemPrices[item] && money >= itemPrices[item];
}

你当前函数中的逻辑有点倒退,canIGet('MacBook Air', 100)返回true的原因是你的第一个if语句为真,因此你的函数返回true。

第一个if语句基本上是这样的:

if (itemPrices["MacBook Air"] >= 100) {

这是true所以你的函数然后返回true,这似乎是向后逻辑。但是,无论如何都没有理由检查所有项目。据推测,您只想使用itemPrices[item]检查您可以执行的项目。

答案 2 :(得分:0)

我愿意;

var itemPrices = {
                    'MacBook Air': 999,
                    'MacBook Pro': 1299,
                        'Mac Pro': 2499,
                  'Apple Sticker': 1  
                 },
       canIGet = (o,p,v) => o[p] <= v;

console.log(canIGet(itemPrices,'MacBook Air',100));