2017-02-12 37 views
0

我目前正在学习JavaScript和所有测试通过,但我的某个函数似乎没有正常运行。JavaScript for-loop不返回项目,测试不通过

这里的测试

it("should get record by its id", function(){ 
    customer1.setFunds(100); 
    customer1.buy(record1, store1); 
    customer1.buy(record2, store1); 
    var item = customer1.getRecord("xyz123"); 
    console.log(customer1); 
    is.equal("Nirvana", item.artist); 
}), 

这里的对象

record2 = new Record("Nirvana", "In Utero", 25, 11, "xyz123");//the last attribute is the id 

这是我正在测试

getRecord: function(id){ 
for(var i = 0; i<this.boughtItems.length; i+=1){ 
if(this.boughtItems[i].id === id){ 
    return this.boughtItems[i]; 
}else{ 
    return "The item doesn't exist"; 
} 
} 

函数的一点是,this.boughtItems由该元素的我我正在寻找和功能无法返回它。我知道JS对象有时会以一种奇怪的方式工作,但这对我来说很模糊。除非我是盲人,看不到一个简单的问题去那里

谢谢!

更新记录不成立分配给它的任何功能,只是属性

var Record = function(artist, title, price, stock, id){ 
this.artist = artist; 
this.title = title; 
this.price = price; 
this.stock = stock; 
this.id = id; 
}; 

UPDATE2买入()方法

buy: function(product, store){ 
if(this.funds >= product.price){ 
    store.sell(product); 
    var itemToBuy = new Record(product.artist, product.title, product.price, 1, product.id); 
    this.boughtItems.push(itemToBuy); 
    this.funds -= itemToBuy.price; 
}else{ 
return "You cannot afford to buy this item"; 
    } 
} 

,这是更加古怪,在我的测试中, “商品”对象显示为“您买不起这个商品”

+1

我们可以看到您正在使用的'Record'原型类吗? – forrestmid

+0

更新:)谢谢! – bwielk

+1

我们可以在Customer上看到'buy()'方法吗? –

回答

0

您需要从您的for-loop中取出您的if。 现在它在第一个元素后面返回“该项目不存在”。

getRecord: function(id) { 
for(var i = 0; i<this.boughtItems.length; i+=1) { 
    if (this.boughtItems[i].id === id) { 
     return this.boughtItems[i]; 
    } 
} 
return "The item doesn't exist"; 
+0

它的工作,但...如何? – bwielk

+0

在你的情况下,只有数组的第一个元素被选中。如果第一个元素正确地返回了该对象,但当它失败时返回“该项不存在”。因为你在for循环中返回了一些东西,所以它会停止迭代。您可以通过在for循环中记录索引来检查这个问题 – bmooij

+0

感谢您的提示!我认为我需要对循环行为更加小心 – bwielk