使用FP时,如何连续编辑待办事项数组?我了解,当您使用诸如.concat()之类的数组方法时,您将返回该数组的副本,而不编辑原始数组。这是我的原始代码,仅将新的待办事项推入todo数组。这将永久更改我们试图避免的myTodos变量。
let myTodos = []
function addTodo(newTodo) {
myTodos.push(newTodo)
return myTodos
}
我已经这样重写了此功能:
const addTodo = (arr, todoText) => arr.concat(todoText)
这工作得很好,但是当我避免使用全局变量时,我不明白如何保留返回的值。如果我调用此方法将第二个待办事项添加到列表中,则由于该var未存储在任何地方,因此只会返回该第二个待办事项。我觉得有一种非常明显的方法可以解决此问题,但我似乎无法弄清楚。
抱歉,我对编程世界还是一个新手。任何帮助将不胜感激。
最佳答案
/*
1) how to avoid global variables?
2) how to not change the original?
3) how to keep the changed
#1 - this is called an Immediately Invoked Functional Expression (IIFE for short)
What this does is lets us create a "scope" within our script. Variables we
create inside it with `var` or `let` or `const`, are not global. They will
only exist inside the scope.
*/
(function(){
var originalArray = [];
// #2 - concat does not change the original array
// #3 - to keep the change, just store it in another variable
var changedArray = originalArray.concat('me');
// #3 - if I want to make more changes, I use the new variable
changedArray = changedArray.concat('yet another value');
console.log(originalArray);
console.log(changedArray);
}());