2017-02-12 35 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