【发布时间】:2017-07-16 17:12:22
【问题描述】:
我正在使用 Vue 和 Rails。下面代码的目标是当用户在添加新配方和返回主页面之间切换时从输入字段中删除文本。这适用于我所有的领域,除了成分。
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);
}
}
}
},
配方对象代码
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
【问题讨论】:
-
为什么不只是
this.recipes.ingredients = []而不是循环遍历每个,因为您只想重置对象?
标签: javascript arrays loops object vue.js