Wow. Your idea may work, but there's a much cleaner way:
var drag;
for (int i = 0; i < shapes.length; i++) {
if (shapes[i].id == dragID) {
drag = shapes[i];
break;
}
}
if (drag) {
// a matching shape was found
// ...
}
If you want to remove that element from its position in the array, use splice
:
if (shapes[i].id == dragID) {
drag = shapes.splice(i, 1);
break;
}
You definitely don't have to use push
and pop
to go through an array.
EDIT References showing you can access an array using []
The reading is kind of dense, but the specification for ECMA-262 (the latest standard to which JavaScript subscribes) is at http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf. On page 67, it says:
Properties are accessed by name, using either the dot notation:
MemberExpression . IdentifierName
CallExpression . IdentifierName
or the bracket notation:
MemberExpression [ Expression ]
CallExpression [ Expression ]
The [] accessor is actually allowed on all objects, and arrays are special objects. Page 122 defines an array:
Array objects give special treatment to a certain class of property names. A property name P (in the form of a String value) is an array index if and only if ToString(ToUint32(P)) is equal to P and ToUint32(P) is not equal to 2^
32 - 1. A property whose property name is an array index is also called an element. Every Array object has a length property whose value is always a nonnegative integer less than 2^
32.
What this boils down to is "if you use numbers as indices to the properties of an object, that object is treated as an array."
The spec is fairly dense to read, so here are some easier references to using arrays in JavaScript: