PHP code: {code ...} output {code ...} JS code: {code ...} output: {code ...} what I want is that the processing in the function does not affect the function, which is similar to the result of PHP. I also want to know why PHP code:
Output
Array( [0] => 1 [1] => 2 [2] => dddss)Array( [0] => 1 [1] => 2)
JS code:
var $key = [1,2];function addkey($key){ let hello = $key; hello.push(9) console.log(hello) console.log($key)}addkey($key)console.log($key)
Output:
[ 1, 2, 9 ][ 1, 2, 9 ][ 1, 2, 9 ]
What I want is that the processing in the function does not affect the function, that is, the result similar to that in PHP. I also want to know why.
Reply content:
PHP code:
Output
Array( [0] => 1 [1] => 2 [2] => dddss)Array( [0] => 1 [1] => 2)
JS code:
var $key = [1,2];function addkey($key){ let hello = $key; hello.push(9) console.log(hello) console.log($key)}addkey($key)console.log($key)
Output:
[ 1, 2, 9 ][ 1, 2, 9 ][ 1, 2, 9 ]
What I want is that the processing in the function does not affect the function, that is, the result similar to that in PHP. I also want to know why.
Let hello = $ key. slice ();
Your function parameter is an array, and the array is passed by reference in js .. When you use let in the function to assign the reference of an array to another variable. In fact, both hello and $ key point to a value, which is an array with length 2. So when you push or perform other operations on any variable, the change is actually the value pointed to by both variables at the same time.
By default, input parameters in PHP are transmitted copies, not references, but all input parameters in JS are referenced. Therefore, you only need to copy one of them to modify it.
Var $ keys = [1, 2]; function addkey ($ keys) {// Copy a copy of let hello = []. concat ($ keys); hello. push (9); console. log (hello); console. log ($ keys);} addkey ($ keys); console. log ($ keys );
The problem lies in the reference to pass the value. In fact, this will appear in PHP.
$obj = new stdClass();$obj->name = 'aa';function change($o) { $o->name = 'bb';}change($obj);echo $obj; // 'bb'
The difference is that the js array is also an object, and it is also a reference to pass the value. You can search for 'Clone object '. The answer to this question is provided above.
When using php to input parameters, add & that is, reference and pass the value. that's the same as running your js code.