简体   繁体   English

Array.push() 是否在改变数组?

[英]Is Array.push() mutating the array?

I am doing:我在做:

  const array = []

  ...
  array.push({x, y})

Is that considered a bad practise.这被认为是一种不好的做法。 Should I use let or spread the array because "push" is considered a mutating action.我应该使用 let 还是传播数组,因为“push”被认为是一种变异动作。 It is working though.它正在工作。

Is Array.push() mutating the array? Array.push() 是否在改变数组?

Yes是的

Is that considered a bad practise.这被认为是一种不好的做法。 Should I use let or spread the array because "push" is considered a mutating action.我应该使用 let 还是传播数组,因为“push”被认为是一种变异动作。

Generally not.一般不会。

There are times when treating data as immutable is useful, or even essential (such as when you are updating a Redux store).有时将数据视为不可变是有用的,甚至是必不可少的(例如当您更新 Redux 存储时)。

In those cases, push still isn't a bad idea, you just shouldn't do it to your original array.在这些情况下, push仍然不是一个坏主意,您只是不应该对原始数组执行此操作。

For example, this is fine and has no side effects:例如,这很好并且没有副作用:

function functionalFunction(input) {
    const output = [...input];
    output.push({x, y});
    // A bunch of other operations that mutate the array go here
    // Be careful not to mutate any objects in the array
    return output;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM