我想要比较两个数组,如果第一个数组中没有它们,则只将一个数组的值添加到另一个数组中。
我写了这个函数:
class Menu {
constructor(option, name, ingredients) {
this.option = option;
this.name = name;
this.ingredients = [];
}
addIngredient(...ingredient) {
for (var i = 0; i < this.ingredients.length; i++) {
for (var j = 0; ingredient.length; j++) {
if (this.ingredients[i] == ingredient[j]) {
console.log(`The reciple already includes ${ingredient[j]}`);
} else {
this.ingredients = this.ingredients.push(ingredient[j]);
console.log(`${ingredient[j]} has been added`);
}
}
}
}
}
if语句的第一部分正常工作,但是当它是第二种情况时,它返回undefined。我做错了什么?
答案 0 :(得分:2)
function mergeArrays(arr1, arr2) {
arr2.forEach(function(el){
if (arr1.indexOf(el) == -1) {
arr1.push(el);
}
})
}
函数修改arr1
答案 1 :(得分:1)
可能你没有初学这个成分
this.ingredients : any = [];
在推送元素之前,检查它是否为空。您还缺少console.log中的 ]
for (var j = 0; ingredient.length; j++) {
if (this.ingredients[i] == ingredient[j]) {
console.log(`The reciple already includes ${ingredient[j]}`);
} else {
this.ingredients.push(ingredient[j]);
console.log(`${ingredient[j]} has been added`);
}
}
<强> EDIT
强>
替换行,
this.ingredients = this.ingredients.push(ingredient[j]);
与
this.ingredients.push(ingredient[j]);
答案 2 :(得分:1)
您需要检查元素是否存在。这里不需要循环,indexOf
将起作用。然后push
您的参赛作品。 push
不会返回数组。
class Menu {
constructor(option, name, ingredients) {
this.option = option;
this.name = name;
this.ingredients = [];
}
addIngredient(...ingredient) {
for (var i = 0; i < ingredient.length; i++) {
if (this.ingredients.indexOf(ingredient[i]) == -1) {
this.ingredients.push(ingredient[i]);
console.log(`${ingredient[i]} has been added`);
} else {
console.log(`The reciple already includes ${ingredient[i]}`);
}
}
}
}
//lets test
var a = new Menu("Test", "test");
a.addIngredient("a", "b", "c", "a");
使用Andrea的功能:
class Menu {
constructor(option, name, ingredients) {
this.option = option;
this.name = name;
this.ingredients = [];
}
addIngredient(...ingredient) {
mergeArrays(this.ingredients, ingredient);
}
}
function mergeArrays(arr1, arr2) {
arr2.forEach((el) => {
if (arr1.indexOf(el) == -1) {
arr1.push(el);
}
else
{
console.log(`"${el}" already exists in the array.`) //debugging only
}
})
}
//lets test
var a = new Menu("Test", "test");
a.addIngredient("a", "b", "c", "a");