Guys something is really bothering me.
In JavaScript - Arrays are objects, meaning each arrays is allocated with a piece of memory for that datatype.
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.
Why is that the case.
Here is why this returns false in Javascript :
When you create these 2 arrays:
arr1 = [1,2,3];
arr2 = [1,2,3];
you instantiate 2 different Array objects see Array reference . So, even if they have the same elements, they are not the same object, so it returns false.
if you create only one object and copy the reference
to another variable, like this:
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]).
I think that you are familiar with OO, if is not the case, please take a look at this: Object Oriented Programming
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. every doc .
Here is a naive example of how you could compare if 2 arrays have the same elements using 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 . 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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.