为什么要在JS中推送数组引用而不是PHP

Rac*_*ter 3 javascript php

我今天遇到了这个问题,想知道为什么要在php和js中处理数组方面做到这一点。

JS

let x = [];
let i = x;

i.push('test');
console.log(x);
//prints ['test']
Run Code Online (Sandbox Code Playgroud)

的PHP

$x = [];
$i = $x;

array_push($i, 'test');
print_r($x);
/prints []
Run Code Online (Sandbox Code Playgroud)

Rin*_*med 5

在JavaScript x中,引用是通过引用分配的;i而在PHP中,引用是通过值分配的。如果要使其在PHP中运行,应使用:

$i = &$x;
Run Code Online (Sandbox Code Playgroud)

这意味着任何变化$i都会影响$x。参见PHP:参考