0

I need to change array to a new array created inside a function.

function changeArr(a)
{
    a=["hello"];    // don't work
    //a.push("hello");    //works, but the real array pretty big (dont want copy)
}

var arr=[];

changeArr(arr);

console.log(arr); // should echo ["hello"]
holden321
  • 1,166
  • 2
  • 17
  • 32

4 Answers4

2

It seems like all you really want to do is clear the array that is passed into the function, before appending to it:

function changeArr(a)
{        
    a.length = 0;      // clear the array here if you don't care about the prev. contents
    a.push("hello");   // this adds to the array that was passed in
}
Mike Dinescu
  • 54,171
  • 16
  • 118
  • 151
  • 1
    Since the array is being truncated, you can take advantage of a performance optimisation by setting the first element of the array to "hello" instead of calling a method to do it: `a.length = 0; a[0] = "hello";`. – Jakob Jingleheimer Jan 01 '14 at 21:23
1

Inside the function changeArr(), a is only a local variable referencing the array you passed as an argument when calling this function. a=["hello"] makes this local variable reference a newly created and different array. This changes does not affect the original array passed in. What you want to do is likely what Miky Dinescu suggested: use the local variable to modify the original array but don't assign/attach anything new to it.

user3146587
  • 4,250
  • 1
  • 16
  • 25
0

If you are trying to completely replace the array, you can use a return value.

function changeArr()
{
    return ["hello"];
}

arr = changeArr();

If there is a reason you aren't doing this, explain and I'll adjust my answer.

Damien Black
  • 5,579
  • 18
  • 24
0

You can use the splice method as such:

a.splice(0,a.length,"hello")
Thayne
  • 6,619
  • 2
  • 42
  • 67