2017-02-12 9 views
0

現在、JavaScriptとすべてのテストに合格していますが、機能の1つが正しく動作していないようです。JavaScript forループは項目を返しません。テストは成功しません。

ここでテスト

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 

は、ここで私はポイントがthis.boughtItems、その要素Iからなることである

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"; 
} 
} 

をテストしてい機能だだです探している関数は返すことはできません。私は、JSオブジェクトが時には奇妙な方法で動作することを知っていますが、これは私にとって非常に曖昧です。私は目が見えず、そこで起こっている簡単な問題を見ることができない限り、

ありがとう!

UPDATE録音はちょうど属性、それに割り当てられた機能を保持していない

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

アップデート2買い()メソッド

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

カスタマーの 'buy()'メソッドを見ることはできますか? –

答えて

0

あなたのfor-loopからあなたを取り出す必要があります。 最初の要素の後に「アイテムは存在しません」を返します。

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

あなたのケースでは、配列の最初の要素のみがチェックされています。 fist要素がそのオブジェクトを返す要素よりも正しい場合、それが失敗した場合、 "The item does not exist"が返されます。 forループの中で何かを返すので、反復処理は停止します。 forループで 'index'を記録することで確認できます – bmooij

+0

ヒントありがとう!私はループの振る舞いについてもっと注意する必要があると思う – bwielk

関連する問題