Are the elements of Javascript arrays processed in a specific order?

For instance:

var a = []; function p(x) { a.push(x); } [[p(1),p(2)],p(3),[p(4),[p(5)]],p(6)] a == [1,2,3,4,5,6] // Always true? 

Is 'a == [1,2,3,4,5,6]' defined behavior? Can you rely on this?

+4
source share
3 answers

Are the elements of Javascript arrays processed in a specific order?

Yes they are.

Is 'a == [1,2,3,4,5,6]' defined behavior? Can you rely on this?

No, the equals operator does reference equality when comparing an object.

+5
source

The short answer is yes.

Longer answer: your question is actually about JavaScript statements in general, not arrays. The code you sent ( [[p(1),p(2)],p(3),[p(4),[p(5)]],p(6)] ) is not an array, it is An operator that returns an array and also fills the array. JavaScript statements are executed according to the rules of operator precedence .

+2
source

Your question is not very clear, what do you mean by "processed"?

 var a = []; 

This is an array literal, it assigns a reference to an empty array on.

 function p(x) { a.push(x); } 

Each time push () is called, a new element is added to the a.length index (i.e., it is always added after the highest index).

 [[p(1),p(2)],p(3),[p(4),[p(5)]],p(6)] 

This is an array literal that is equivalent to:

 a = []; a[0] = [p(1),p(2)]; a[1] = p(3); a[2] = [p(4),[p(5)]]; a[3] = p(6); 

The following expression:

 a == [1,2,3,4,5,6] 

always false, because arrays are objects and objects are never equal to any other object. You can do:

 var a = [0, 1]; var b = a; a == b; // true since a and b reference the same array 

But

 var a = [0, 1]; var b = [0, 1]; a == b; // false since a and b reference different arrays 
+1
source

Source: https://habr.com/ru/post/1345802/


All Articles