简体   繁体   中英

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. It is working though.

Is Array.push() mutating the array?

Yes

Is that considered a bad practise. Should I use let or spread the array because "push" is considered a mutating action.

Generally not.

There are times when treating data as immutable is useful, or even essential (such as when you are updating a Redux store).

In those cases, push still isn't a bad idea, you just shouldn't do it to your original array.

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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