将JavaScript数组传递给函数

Passing JavaScript arrays to functions

本文关键字:函数 JavaScript 数组      更新时间:2023-09-26

关于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);

这是正确的吗?它是如何工作的?

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]