admin 管理员组

文章数量: 1087134

I can't figure out why my function doesn't change the global variable (arrayValue) It changes it only inside the function, but I want to change it outside.

function reverseArrayInPlace(arrayValue) {
  var newArr = [];
  for (var i = 0; i < arrayValue.length; i++) {
    newArr.unshift(arrayValue[i]);
  }
  arrayValue = newArr;
  return arrayValue;
}
var arrayValue = [1, 2, 3, 4, 5];
reverseArrayInPlace(arrayValue);
console.log(arrayValue); // It gives [1, 2, 3, 4, 5] instead of [5, 4, 3, 2, 1]
console.log(reverseArrayInPlace(arrayValue)); // It gives [5, 4, 3, 2, 1]

I can't figure out why my function doesn't change the global variable (arrayValue) It changes it only inside the function, but I want to change it outside.

function reverseArrayInPlace(arrayValue) {
  var newArr = [];
  for (var i = 0; i < arrayValue.length; i++) {
    newArr.unshift(arrayValue[i]);
  }
  arrayValue = newArr;
  return arrayValue;
}
var arrayValue = [1, 2, 3, 4, 5];
reverseArrayInPlace(arrayValue);
console.log(arrayValue); // It gives [1, 2, 3, 4, 5] instead of [5, 4, 3, 2, 1]
console.log(reverseArrayInPlace(arrayValue)); // It gives [5, 4, 3, 2, 1]
Share Improve this question asked Mar 15, 2017 at 13:13 TgralakTgralak 1473 silver badges11 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 8

Main source of confusion is that the param name of your function and your global array name got conflicted.

You are not modifying the global array, you are modifying the array which is local to that function.

You have two options now.

1) Receive the modified array

reverseArrayInPlace(arrayValue);

That function is returning modified array and you are not receiving it. Hence it is pointing to the old array.

arrayValue  = reverseArrayInPlace(arrayValue);

2) Have unique naming for function param and global array.

The main problem in your question...

why my function doesn't change the global variable?

... is that you're mistaking the parameter in your function (named arrayValue) with your global (also named arrayValue).

You can easily see this if you give your function another parameter:

function reverseArrayInPlace(arrValue) {
  var newArr = [];
  for (var i = 0; i < arrValue.length; i++) {
    newArr.unshift(arrValue[i]);
  }
  arrayValue = newArr;
}

var arrayValue = [1, 2, 3, 4, 5];

reverseArrayInPlace(arrayValue);

console.log(arrayValue);

Note that in this snippet the function is not returning anything (actually it's returning undefined), just changing your global.

本文标签: arraysCan39t change global variable inside a function (Javascript)Stack Overflow