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"]
1

4 Answers 4

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
}
Sign up to request clarification or add additional context in comments.

1 Comment

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";.
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.

Comments

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.

Comments

0

You can use the splice method as such:

a.splice(0,a.length,"hello")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.