The difference between php and node (2) -- function parameter reference

$a = [1,3];
function change_arr($arr) {
    $arr[0] = 200;
}
change_arr($a);
var_dump($a);

php prints the result as follows:
array(2) {
  [0]=>
  int(1)
  [1]=>
  int(3)
}


That is to say, php does not change the original actual parameters.
If you want to change, there are two ways,
the first is to change the function definition
$a = [1,3];
function change_arr(&$arr) { // only add a pass by reference here
    $arr[0] = 200;
}
change_arr($a);
var_dump($a);


Type 2: Use the return value
$a = [1,3];
function change_arr($arr) {
    $arr[0] = 200;
    return $arr;
}
$a = change_arr($a);
var_dump($a);


The above two ways of writing will lead to changes.
The result is as follows:
array(2) {
  [0]=>
  int(200)
  [1]=>
  int(3)
}


===================================================== =====================================================
_ ===================================

Start node here
var arr = [1,3];
function change_arr(arr2){
    arr2[0] = 200;
}

change_arr(arr);
arr.map((n)=>{
    console.log(n);
})


Good guy, modify the actual parameters directly.
Below is the print result
200
3


So node programming should be careful ~

previous link:
Difference between php and node (1) -- scope

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326524596&siteId=291194637