变异的JavaScript数组中功能 [英] Mutate JavaScript Array Inside Function
问题描述
在JavaScript中,我怎么变异函数内部数组的价值呢?我知道,使用某些阵列方法时,会发生,但它似乎并没有正常工作分配。
In JavaScript, how do I mutate the value of an array inside of a function? I know that happens when using certain array methods, but it doesn't seem to work for normal assignment.
var arr = [4]
function changeArray(arr) {
arr = [1,2,3];
}
// arr is still equal to [4]. I want it to equal [1,2,3].
这是我的理解是,这code不改变功能的常用3以外的值。我该怎么办呢在变异被作为参数传递数组的方法吗?
It's my understanding that this code doesn't change the value of "arr" outside of the function. How can I do it in a way that mutates the array that was passed as an argument?
推荐答案
您可以使用的 .splice
:
You can use .splice
:
arr.splice(0, arr.length, 1, 2, 3);
或者你可以清空阵列和 .push
值:
arr.length = 0;
arr.push(1, 2, 3);
// or given an array of values
arr.push.apply(arr, newValues);
但是,请务必很显然,该函数改变数组的在的。虽然有本地函数做这个(如阵列#排序
),我认为这是不常见的简单地返回一个新的数组。
However, make sure it is clear that the function changes the array in place. While there are native functions that does this (like Array#sort
), I'd argue that this is not as common as simply returning a new array.
这是我的理解是,这code不会改变的常用3的功能之外的价值。
It's my understanding that this code doesn't change the value of "arr" outside of the function.
正确的。分配一个新的值到一个变量或属性的从不改变的另一个变量或属性的值(例外:以声明全局范围和)。
你基本上试图改变一个变量的值,而不是突变本身的价值。
Correct. Assigning a new value to a variable or property never changes the value of another variable or property (exceptions: global scope and with
statements).
You basically tried to change the value of a variable, not mutate the value itself.
JavaScript是呼叫/传/分配 按值的 (维基百科也提到分享),而不是< A HREF =http://en.wikipedia.org/wiki/Call_by_reference#Call_by_reference相对=nofollow>按引用 的
JavaScript is call/pass/assign by value (Wikipedia also mentions "by sharing"), not by reference.
这篇关于变异的JavaScript数组中功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!