在Javascript代码中:
var people = [{name:"john",age:20},{name:"bob",age:30},{name:"kate",age:40}];
people.forEach(function(person,i){
person.isHuman = true;
})
console.log(people)会给予
[{{name:“ john”,age:20,isHuman:true},{name:“ bob”,age:30,isHuman:true},{name:“ kate”,age:40,isHuman:true }]
但是,PHP中的相同代码
$people = [["name"=>"john","age"=>20],["name"=>"bob","age"=>30],["name"=>"kate","age"=>40]];
foreach($people as $i=>$person){
$person['isHuman']=true;
}
var_dump($ people)会给予
[[“” name“ =>” john“,” age“ => 20],[” name“ =>” bob“,” age“ => 30],[” name“ =>” kate“, “ age” => 40]]
新的“ isHuman”属性未添加到原始对象数组。
在PHP的情况下,我知道您可以执行“ $ people [$ i] ['isHuman'] = true”来更改原始数组中的对象。但是,有没有一种方法可以做到“ $ person ['isHuman'] = true”并使更改反映在原始数组中?
我的第二个问题是,为什么/为什么Java和PHP之间的行为不同?