我在做:
const array = []
...
array.push({x, y})
Run Code Online (Sandbox Code Playgroud)
这被认为是一种不好的做法吗?我应该使用 let 还是 spread 数组,因为“push”被认为是一种变异操作。但它正在发挥作用。
Array.push() 是否会改变数组?
是的
这被认为是一种不好的做法吗?我应该使用 let 还是 spread 数组,因为“push”被认为是一种变异操作。
一般不会。
有时将数据视为不可变是有用的,甚至是必要的(例如当您更新 Redux 存储时)。
在这些情况下,push
仍然不是一个坏主意,您只是不应该对原始数组执行此操作。
例如,这很好并且没有副作用:
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;
}
Run Code Online (Sandbox Code Playgroud)