我有以下功能:
var groceries = ["toothpaste", ["plums", "peaches", "pineapples"], ["carrots", "corn", "green beans"], "orange juice", ["chocolate", "ice cream"], "paper towels", "fish"];
console.log("groceries", groceries);
function removeItems(arr, toRemove) {
function createKey(item) {
return Array.isArray(item) ? item.join('-') : item;
}
var removeDict = toRemove.reduce(function(d, item) {
var key = createKey(item);
d[key] = true;
return d;
}, {});
console.log("removeDict", removeDict);
return arr.filter(function(item) {
var key = createKey(item);
return !removeDict[key];
});
}
var result = removeItems(groceries, ["fish", "orange juice", ["chocolate", "ice cream"]]);
console.log("result", result);
(这来自我之前提出的问题): function to remove single items or arrays from within an array - javascript
如果我在调用函数的末尾创建一个变量,它会在控制台中正确打印。
但是,如果我尝试直接调用该函数,请执行以下操作:
removeItems(groceries, ["fish", "orange juice", ["chocolate", "ice cream"]]);
console.log("groceries", groceries);
不会删除这些项目。为什么我不能直接调用该函数?我错过了什么吗?
答案 0 :(得分:1)
数组过滤器方法返回一个新的过滤数组。
因此,您的原始数组不会发生变异。
如果将结果存储在变量中,则可以将其记录下来:
var newArr = removeItems(groceries, ["fish", "orange juice", ["chocolate", "ice cream"]]);
console.log("groceries", newArr)