For example:
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 it be relied upon?
3 Answers 3
Are elements of Javascript arrays processed in a defined order?
Yes they are.
Is 'a == [1,2,3,4,5,6]' defined behavior? Can it be relied upon?
No, the equals operator performs referential equality when comparing object.
-
In what way are "elements of Javascript arrays processed in a defined order?". The order that properties are returned by for..in is implementation dependent (and is different for various browsers). The only other "processing order" is the order that expressions are evaluated, which has nothing specifically to do with arrays.RobG– RobG2011年04月27日 01:40:40 +00:00Commented Apr 27, 2011 at 1:40
Short answer: "Yes".
Longer answer: Your question is actually about JavaScript statements in general and not Arrays. The code you posted ([[p(1),p(2)],p(3),[p(4),[p(5)]],p(6)]
) is not an Array, it is a statement that returns an Array whilst also populating an Array. JavaScript statements are executed according to the rules of operator precedence.
Your question is not very clear, what do you mean by "processed"?
var a = [];
That is an array literal, it assigns a reference to an empty array to a.
function p(x) { a.push(x); }
Each time push() is called, a new element is added to a at index a.length (i.e. it is always added after the highest index).
[[p(1),p(2)],p(3),[p(4),[p(5)]],p(6)]
That 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]
is always false, since 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
[[p(1),p(2)],p(3),[p(4),[p(5)]],p(6)]
is processed from left to right, so yes, after it is evaluated,a
will be[1,2,3,4,5,6]
always (for implementations that supportarray.push()
of course). The result of the literal itself though is[[undefined, undefined], undedfined, [undedfined, [undedfined]], undedfined]
sincep()
has noreturn
statement, it will return undefined.