Why does the first function not modify the original array like the second function does?
var a= [3, 4, 5];
function doesNothing(a) {
a=[1,1,1];
}
function doesSomething(a) {
a.push(6);
}
doesNothing(a);
console.log(a); // [3,4,5] not [1,1,1]
doesSomething(a);
console.log(a); //[3,4,5,6]
That is, there is only one array -- and that same array is changed inside the function. If you wish to be able to change it without fear of affecting the outside, make a copy first. For a simple array this can be done with Array. prototype.
The modern, and easiest way to pass an array to a function is to use the spread operator. The spread operator ( ... ) is simply added before the array.
push() adds item(s) to the end of an array and changes the original array. unshift() adds an item(s) to the beginning of an array and changes the original array. splice() changes an array, by adding, removing and inserting elements. slice() copies a given part of an array and returns that copied part as a new array.
Given an array, we need to modify values of this array in such a way that sum of absolute differences between two consecutive elements is maximized. If the value of an array element is X, then we can change it to either 1 or X.
The first function makes no attempt to modify the array. All it does is assign a new value to the parameter that, when it was called, was given a copy of a reference to the array. The variable a
in the first function is just a variable with an object reference as its value. The assignment statement just changes its value, exactly as if your function had
a = 5;
instead.
Note that you've declared the first function with a
as a parameter - that symbol a
hides the a
outside the function.
The second function does modify the array because it calls a method on the array object that modifies it.
Because in your first function, the statement a =
initializes a new variable in local scope (it essentially translates to var a =
) completely unrelated to the global a
variable, whereas in the second function, you're calling upon and mutating the original array passed into it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With