[英]Can't change array passed inside function
Let's say we have an array a = [1,2,3,4,5]
and I want to zero it [0,0,0,0,0]
by using function.假设我们有一个数组
a = [1,2,3,4,5]
,我想通过使用函数将它归零[0,0,0,0,0]
。 This works:这有效:
function clear (arr) {
arr.forEach((element, index) => {arr[index] = 0});
}
But this don't:但这不会:
function clear2 (arr) {
arr = [...arr].fill(0);
}
Just arr.fill(0)
inside clear2()
works, but it's running inside Vue.js so I can't assign array elements by index, I need to reassign array var completely to remain reactivity. clear2() 中的
arr.fill(0)
clear2()
,但它在 Vue.js 中运行,因此我无法按索引分配数组元素,我需要完全重新分配数组 var 以保持反应性。
Why clear2()
doesn't work?为什么
clear2()
不起作用? Arrays as a case of Objects should be passed by reference, so what am I doing wrong?数组作为对象的情况应该通过引用传递,那么我做错了什么?
Update: I use it as a on-click method in Vue so I can't return from it and want to pass different arrays as a parameter.更新:我在 Vue 中将它用作单击方法,因此我无法从它返回并希望将不同的数组作为参数传递。
With和
arr = [...arr].fill(0);
you're creating a copy of the original array then chaning that copy's values and then setting the parameter's reference value to the new array (you're not updating the parameter's inner state)您正在创建原始数组的副本,然后更改该副本的值,然后将参数的引用值设置为新数组(您没有更新参数的内部状态)
with和
arr.forEach((element, index) => {arr[index] = 0});
you're actually updating the array parameter inner state您实际上是在更新数组参数内部状态
You could use fill
directly, because你可以直接使用
fill
,因为
The
fill
method is a mutable method, it will change this object itself, and return it, not just return a copy of it.fill
方法是一个可变方法,它会改变这个对象本身,并返回它,而不仅仅是返回它的一个副本。
function clear(array) { array.fill(0); } var array = [1, 2, 3, 4]; clear(array); console.log(array);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.