1

Issue is demonstrated in this plunker: https://plnkr.co/edit/h1fFuY9VOZDLHO5JAM3o

I know that all arrays in Typescript are passed by reference. Thus it should be possible to assign new array to this reference.

But I've got a problem. If I want to replace one array with another from inside of the method in Angular 6.1.7 (TS 2.9.2), changes are not visible from outside of the method.

private assignArray(arrayToReplace: any[], replacement: any[]) {
    arrayToReplace = replacement;
}

I've found workaround to this problem. Instead of assigning source array to target array, I remove all entries from target array and push all entries of source array in it.

private replaceArray(arrayToReplace: any[], replacement: any[]) {
    arrayToReplace.splice(0, arrayToReplace.length);
    for(let c of replacement) {
        arrayToReplace.push(c);
    }
}

Actually, this plunker behaves strange because console shows that array was changed even before invocation of replaceArray() method.

So it this behavior a bug of Angular/Typescript?

1 Answer 1

1

You are right that array is passed by reference, but you get the copy of the reference in your method. So when you modify the reference you modify its copy. There are no modifiers like out or ref that could help you. I suggest you return the new array that you try to return via a parameter.

Sign up to request clarification or add additional context in comments.

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.