我的代码中有一个错误,但我无法找到它。
首先,这是我的方法:
async getRandomMeals() {
let that = this;
let meals = [];
let recipeList = await this.appData.getRecipeList(); // {title: "someTitle", ...}, {title: "meal",...} from local stroage
let excludedIngredients = await this.appData.getItem("excludedIngredientsArray") || []; // get from local storage
let mealsProfile = await this.appData.getItem("mealsProfile"); // get from local storage
let filterRecipeList = recipeList;
if (excludedIngredients.length > 0) {
filterRecipeList = this.filterRecipeListByExcludes(recipeList, excludedIngredients)
}
for (let i = 0; i <= 6; i++) {
meals.push(mealsProfile);
}
meals.forEach((day) => {
day.forEach((daytime) => {
daytime.meals = filterRecipeList.filter(x => {
return x.daytime.includes(daytime.slug.toLowerCase())
&& x.difficultyNumber <= daytime.difficulty
}).sort(function () { // <-- this dont work
return 0.5 - Math.random()
});
});
});
console.log(meals);
return meals;
}
我的问题:
到目前为止一切正常,但是饭菜应该是随机的,由于某些原因,随机化不起作用。
问题不在于,我无法随机化阵列。随机化本身很有用,但不适用于此&#34; filterRecipeList&#34;阵列。
如果有人得到一个提示,或者为什么随机化的东西不起作用,我会很高兴。
修改
这也不起作用:
filterRecipeList = filterRecipeList.sort(function () {
return 0.5 - Math.random()
});
编辑2:
我现在有一个肮脏的解决方案,看起来像这样:
await this.appData.setItem("tmpMealPlan", mealPlan); // save to local storage
let finalMealPlan = await this.appData.getItem("tmpMealPlan"); // get again from local storage
finalMealPlan.forEach((day) => {
day.forEach((daytime) => {
daytime.meals = daytime.meals.sort(function () {
return 0.5 - Math.random()
}).slice(0,4);
});
});
return finalMealPlan;
出于某种原因,这种方法很好,但看起来很糟糕:D