我目前正在學習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";
}
}
,這是更加古怪,在我的測試中, 「商品」對象顯示爲「您買不起這個商品」
我們可以看到您正在使用的'Record'原型類嗎? – forrestmid
更新:)謝謝! – bwielk
我們可以在Customer上看到'buy()'方法嗎? –