将JavaScript数组传递给函数

时间:2016-05-18 21:04:33

标签: javascript arrays function

关于JavaScript的一般问题。如果我有一个修改数组的函数,例如:

var some_array = [];

function a_function(input, array){

    //do stuff to array
    return array;

}

在大多数语言中:

var some_array = [];

some_array = a_function(input, some_array);

console.log(some_array);

有效,但是在js中,下面也有效:

var some_array = [];

a_function(input, some_array);

console.log(some_array);

这是正确的,这是如何工作的?

1 个答案:

答案 0 :(得分:4)

JS中的数组是对象,并按值传递给函数,其中该值是对数组的引用。换句话说,作为参数传递给函数的数组仍然指向与外部数组相同的内存。

这意味着更改函数中的数组内容会更改从函数外部传递的数组。



function f(arr) {
  arr.push(1); 
  return arr;
}

var array = [];

// both function calls bellow add an element to the same array and then return a reference to that array. 

// adds an element to the array and returns it.
// It overrides the previous reference to the array with a 
// new reference to the same array.
array = f(array);
console.log(array); // [1]

// adds an element to the array and ignores the returned reference.
f(array);
console.log(array); // [1, 1]




相关问题