2017-02-25 65 views
0

我正在使用Vue和Rails。以下代碼的目標是當用戶在添加新配方和返回主頁之間切換時,從輸入字段中刪除文本。這適用於所有我的領域,除了配料。循環瀏覽JavaScript對象數組並刪除值

成分是一個屬於配方對象的數組,它包含一個鍵值對中的名稱。我想通過這個循環,並刪除所有的成分。我通過調用removeIngredients函數來做到這一點。問題是當我執行下面的代碼時,循環只抓取每一個其他索引,因此只有一半的成分被刪除。

resetNewRecipe: function(){ 
    this.recipe.name = ''; 
    this.recipe.chef = ''; 
    this.recipe.cooktime = ''; 
    this.recipe.amount = '', 
    this.recipe.description = ''; 
    this.recipe.favorite = false; 
    this.recipe.ingredients.name = ''; 
    for (i = 0; i < this.recipe.ingredients.length; i++){ 

     for (var name in this.recipe.ingredients[i]){ 

     if (this.recipe.ingredients[i].hasOwnProperty(name)){ 
      console.log("name = " + name); 
      console.log("i = " + i); 
      console.log("this.recipe.ingredients[i][name] " + this.recipe.ingredients[i][name]); 

      this.removeIngredient(i); 
     } 
     } 
    } 
    }, 

配方目標代碼

recipe: { 
    name: '', 
    chef: '', 
    cooktime: '', 
    amount: '', 
    description: '', 
    favorite: false, 
    ingredients: [ 
     {name: ''}, 
    ]} 

CONSOLE.LOG當我創建的每個命名1,2,3,4四種成分返回。基本上1和3成功通過並被刪除,而當我回到表單時2和4保持不變。

name = name 
i = 0 
this.recipe.ingredients[i][name] 1 

name = name 
i = 1 
this.recipe.ingredients[i][name] 3 
+1

爲什麼不只是'this.recipes.ingredients = []'而不是循環遍歷每一個,因爲你只是想重置對象? –

回答

0

向後迭代遍歷數組,所以從最後一個索引到0。這樣你就可以將它們全部刪除。當你實際刪除一個時,你應該跳出內循環:

for (var i = this.recipe.ingredients.length - 1; i >= 0; i--){ // <-- change direction 
    for (var name in this.recipe.ingredients[i]){ 
    if (this.recipe.ingredients[i].hasOwnProperty(name)){ 
     this.removeIngredient(i); 
     break; // <------ add this 
    } 
    } 
} 
+0

這樣做。非常感謝你的幫助。 – Mahler7

+0

不客氣:-) – trincot

+0

完成並再次感謝。 – Mahler7