我有以下功能:
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);
(这来 self 之前提出的问题): function to remove single items or arrays from within an array - javascript
如果我在调用该函数的末尾创建一个变量,它会在控制台中正确打印。
但是,如果我尝试直接调用该函数,如下所示:
removeItems(groceries, ["fish", "orange juice", ["chocolate", "ice cream"]]);
console.log("groceries", groceries);
这些项目不会被删除。为什么我不能直接调用该函数?我错过了什么吗?
最佳答案
数组过滤方法返回一个新的过滤数组。
因此,您的原始数组没有发生变化。
如果将结果存储在变量中,则可以将其记录下来:
var newArr = removeItems(groceries, ["fish", "orange juice", ["chocolate", "ice cream"]]);
console.log("groceries", newArr)
关于javascript - 为什么我无法调用函数但可以在控制台中打印它? javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45953413/