[英]comparing arrays in php and in javascript return 2 different values. Why?
Guys something is really bothering me. 伙计们真的很困扰我。
In JavaScript - Arrays are objects, meaning each arrays is allocated with a piece of memory for that datatype. 在JavaScript中-数组是对象,这意味着每个数组都为该数据类型分配了一块内存。
So that makes sense when 所以这在什么时候有意义
arr1 = [1,2,3]
arr2 = [1,2,3]
arr1 == arr2 returns false
HOWEVER 然而
In php that same scenario returns true. 在php中,相同的情况返回true。
Why is that the case. 为什么会这样。
Here is why this returns false in Javascript : 这就是在Javascript中返回false的原因:
When you create these 2 arrays: 创建这两个数组时:
arr1 = [1,2,3];
arr2 = [1,2,3];
you instantiate 2 different Array objects see Array reference . 实例化2个不同的Array对象, 请参见Array参考 。 So, even if they have the same elements, they are not the same object, so it returns false.
因此,即使它们具有相同的元素,它们也不是同一对象,所以它返回false。
if you create only one object and copy the reference
to another variable, like this: 如果仅创建一个对象,然后将
reference
复制到另一个变量,例如:
var arr1 = [1,2,3];
var arr2 = arr1
(arr1 == arr2) //returns true
it will returns true because they have the reference to the same object([1,2,3]). 它会返回true,因为它们具有对同一对象([1,2,3])的引用。
I think that you are familiar with OO, if is not the case, please take a look at this: Object Oriented Programming 我认为您熟悉OO,如果不是这样,请看一下: 面向对象编程
So, if you need to compare if each element of an array is equal to another in the same index you use the native function every()
as @Prafulla Kumas Sahu mentioned. 因此,如果需要比较同一索引中数组的每个元素是否等于另一个元素,则可以使用@Prafulla Kumas Sahu提到的本机函数
every()
。 every doc . 每个文档 。
Here is a naive example of how you could compare if 2 arrays have the same elements using every()
: 这是一个朴素的示例,说明如何使用
every()
比较两个数组是否具有相同的元素:
var arr1 = [1,2,3];
var arr2 = [1,2,3];
arr1.every(function(value, index){
return value == arr2[index];
});
//returns true
In PHP there are extra native
operators for Arrays in the PHP language, php docs . 在PHP中,PHP语言php docs提供了数组的其他
native
运算符。 They can check: 他们可以检查:
So, it's false in javascript because the operator == check if the instance
of an Array object has the same reference
to another. 因此,在javascript中是错误的 ,因为运算符==检查Array对象的
instance
是否具有对另一个对象的相同reference
。
And it's true in PHP because there are extra operators
for arrays, and the operator == check if two different arrays have the same pair value. 这在PHP中是正确的 ,因为数组有
extra operators
,并且==运算符检查两个不同的数组是否具有相同的对值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.