如何在不使用全局变量的情况下编辑待办事项列表 函数式编程 Vanilla JS

How to Edit Todo List Without Using Global Variables Functional Programming Vanilla JS

您如何在使用 FP 的同时不断编辑一系列待办事项?我知道当您使用诸如 .concat() 之类的数组方法时,您正在 return 复制数组而不是编辑原始数组。这是我的原始代码,它只是将一个新的待办事项推送到待办事项数组。这会永久更改我们试图避免的 myTodos 变量。

let myTodos = []

function addTodo(newTodo) {
  myTodos.push(newTodo)
  return myTodos
}

我重写了这个函数:

const addTodo = (arr, todoText) => arr.concat(todoText)

这工作得很好,但我不明白如何在我应该避免使用全局变量时保留 returned 的值。如果我调用它来将第二个待办事项添加到我的列表中,它只会 return 第二个待办事项,因为 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);
    }());