标签:数组和关联数组 引用类型 关联 var 一个 分类 === 返回值 array
一、分类与创建
1:JS的数组都是索引数组,数组是一种特殊的对象,创建数组的方式有两种
//方式一 var arr1 = [‘关羽‘, ‘张飞‘, ‘赵云‘, ‘马超‘, ‘黄忠‘]; //方式二 var arr2 = new Array(); arr2[0] = ‘关羽‘; arr2[1] = ‘张飞‘; arr2[2] = ‘赵云‘; arr2[3] = ‘马超‘; arr2[4] = ‘黄忠‘;
2:PHP数组分为索引数组和关联数组,创建方式也有两种
//方式一(索引数组) $arr1 = [‘关羽‘, ‘张飞‘, ‘赵云‘, ‘马超‘, ‘黄忠‘]; //方式二(关联数组) $arr2 = array(‘一‘=>‘关羽‘, ‘二‘=>‘张飞‘, ‘三‘=>‘赵云‘, ‘四‘=>‘马超‘, ‘五‘=>‘黄忠‘);
二、JS数组赋值是引用传递,而PHP赋值的是一个副本
var arr1 = [‘关羽‘, ‘张飞‘, ‘赵云‘, ‘马超‘, ‘黄忠‘]; var arr2 = [‘关羽‘, ‘张飞‘, ‘赵云‘, ‘马超‘, ‘黄忠‘]; alert(arr1 == arr2); //输出false
$arr1 = array(‘关羽‘, ‘张飞‘, ‘赵云‘, ‘马超‘, ‘黄忠‘); $arr2 = array(‘关羽‘, ‘张飞‘, ‘赵云‘, ‘马超‘, ‘黄忠‘); echo $arr1 === $arr2; //输出1
JS 对象常称为引用类型,对象的比较均是引用的比较 ,当它们引用同一基对象时,才相等,而php除了 object 外,
其他类型变量大多在赋值、参数传递、返回值中得到都是它的副本, 很少使用按址传递(引用传递),如下:
$arr1 = array(‘关羽‘, ‘张飞‘, ‘赵云‘, ‘马超‘, ‘黄忠‘); $arr2 = &$arr1; //引用传递 $arr1[5] = ‘魏延‘; echo $arr1 === $arr2; //仍然输出1,$arr2随$arr1改变
三、由于JS不支持关联数组,所以PHP中json_encode()只将索引数组转为数组格式,而将关联数组转为对象格式。
$arr1 = array(‘one‘, ‘two‘, ‘three‘, ‘four‘, ‘five‘); echo json_encode($arr1); //索引数组转换为数组格式["one","two","three","four","five"]
$arr2 = array(‘1‘=>‘one‘, ‘2‘=>‘two‘, ‘3‘=>‘three‘, ‘4‘=>‘four‘, ‘5‘=>‘five‘); echo json_encode($arr2); //关联数组转换为对象格式 {"1":"one","2":"two","3":"three","4":"four","5":"five"}
标签:数组和关联数组 引用类型 关联 var 一个 分类 === 返回值 array
原文地址:https://www.cnblogs.com/splendid/p/9742656.html