admin管理员组文章数量:1429844
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.
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.
Share Improve this question asked Dec 8, 2020 at 8:53 Chrissi GrilusChrissi Grilus 1,4153 gold badges14 silver badges23 bronze badges 5- 5 Depends - do you want to avoid mutating the array? Note that a mutation is not bad by itself, depends on your use case. – VLAZ Commented Dec 8, 2020 at 8:54
- I'm exaggerating, but it's like asking "is it OK to add two numbers or should I multiply them?". It really depends on how you want/need from the result. – Felix Kling Commented Dec 8, 2020 at 8:55
- I don't understand the question, are you unsure about what does mutate means? (the title implies you seems unsure about that, but the body is a bit different) – Pac0 Commented Dec 8, 2020 at 8:55
-
"Should I use let". Are you under the impression that you are not allowed
push
to arrays defined withconst
? You are NOT allowed to reassign the variables withconst
likearray = [1,2]
. You are allowed to mutate the arrays and objects by changing their properties. Likeconst a = {}
anda.key1 = 'value'
is allowed. But,a = { key2: 'value 2 '}
is not allowed – adiga Commented Dec 8, 2020 at 9:23 - Its exactly that usecase. An array to wich I push an object. I can see now that mutating the array is usually not a problem and can be done with const. – Chrissi Grilus Commented Dec 8, 2020 at 10:58
1 Answer
Reset to default 6Is 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;
}
本文标签: javascriptIs Arraypush() mutating the arrayStack Overflow
版权声明:本文标题:javascript - Is Array.push() mutating the array? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745452859a2658966.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论