私はVueとRailsを使っています。以下のコードの目的は、ユーザーが新しいレシピの追加とメインページへの切り替えを切り替えるときに入力フィールドからテキストを削除することです。これは成分を除いて私のすべてのフィールドで機能します。オブジェクトのJavaScript配列によるループと値の削除
Ingredientsは、レシピオブジェクトに属し、キー値のペアに名前を保持する配列です。私はこれをループしてすべての成分を取り除きたい。私は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);
}
}
}
},
私は1,2,3,4という名前の4つの成分それぞれを作成するときにレシピオブジェクトコード
recipe: {
name: '',
chef: '',
cooktime: '',
amount: '',
description: '',
favorite: false,
ingredients: [
{name: ''},
]}
にconsole.logを返します。基本的に1と3は正常に渡され、削除されますが、2と4はフォームに戻るときに残ります。
name = name
i = 0
this.recipe.ingredients[i][name] 1
name = name
i = 1
this.recipe.ingredients[i][name] 3
理由だけではなく、 'this.recipes.ingredientsの= []'代わりにあなただけのオブジェクトをリセットするので、それぞれをループの? –