函数式编程 JS 中的数组赋值

Array Assignment in Functional Programming JS

当在函数内部声明一个新的局部变量并将其赋值给一个等于数组的全局变量时,哪个更好?

选项 1:使用扩展运算符:

let globalArray = [1, 2, 4];

function add (arr, value) {

  let newArray = [...arr];

  newArray.push(value);
  return newArray;
  
}

console.log(add(globalArray, "red"));

选项 2:不使用展开运算符:

let globalArray = [1, 2, 4];

function add (arr, value) {

  let newArray = arr;

  newArray.push(value);
  return newArray;
  
}

console.log(add(globalArray, "red"));

我看不出输出有什么不同。是否应该使用传播运算符?

没有标准就没有“更好”,尽管我们可以在这里推断出一些标准。 :-)

使用 push 而不制作副本(您的“NOT”选项)改变 传递给您的函数(全局函数)的原始数组,这通常不是在函数式编程中完成。 FP 倾向于使用不可变数据结构和纯函数(松散地:没有副作用的函数)。

如果您不想改变全局数组,请使用 spread 或 concat 或类似的方法。例如,使用扩展语法(不需要 push 之后,我们可以在数组文字中包含 value):

let newArray = [...arr, value];

let globalArray = [1, 2, 4];

function add (arr, value) {
    const newArray = [...arr, value];
    return newArray;
}

const updated = add(globalArray, "red");
console.log(updated);
console.log(updated === globalArray); // false
console.log(globalArray); // unchanged
.as-console-wrapper {
    max-height: 100% !important;
}

如果你想改变全局数组,在传入的数组上使用push

let globalArray = [1, 2, 4];

function add (arr, value) {
    let newArray = arr;
    newArray.push(value);
    return newArray;
}

const updated = add(globalArray, "red");
console.log(updated);
console.log(updated === globalArray); // true!
console.log(globalArray); // changed!
.as-console-wrapper {
    max-height: 100% !important;
}

...但同样,这通常不会在 FP 中完成。据我了解(我对 FP 并不深入),即使你想更新 globalArray,你通常会通过重新分配它来完成:globalArray = add(globalArray, "red").