Passing variable by full reference

前端 未结 2 1365
故里飘歌
故里飘歌 2021-01-24 03:33

I want to pass an object or array to a function, make it undefined, and see the changes after the function execution ends.

var arr = [\'aaa\', \'bbb\', \'ccc\'];         


        
相关标签:
2条回答
  • 2021-01-24 03:51

    JavaScript is a pass by value language, so modifying the value of a function parameter inside the function cannot have an effect on the variable passed as the argument.

    If you want to do something like that, you can have your function return the value:

    var reset = function(param) {
      // think think think
      if (whatever)
        return undefined;
      return param;
    };
    
    arr = reset(arr);
    

    Now, if the function decides that the right thing to do is empty out the source variable, it returns undefined.

    If you just want to clear the variable, however, there's no need for a function:

    arr = undefined;
    
    0 讨论(0)
  • 2021-01-24 04:02

    You can't pass a variable by reference in JavaScript. What you can do instead, if the variable is in the same or greater scope than reset(), is use the variable itself inside the function as shown below:

    var
      arr = ['aaa', 'bbb', 'ccc'],
      reset = function () {
        arr = undefined;
      }
    
    reset();
    console.log(arr);

    Or instead you can just make it equal to undefined:

    var arr = ['aaa', 'bbb', 'ccc'];
    arr = undefined;
    console.log(arr);

    0 讨论(0)
提交回复
热议问题