wrote:
> I am new to JavaScript but not to programming. What's the best way of
> getting an array of all the values for an attribute in an object
> array?
If you want to understand any language, take care of your vocabulary.
Objects are an unordered collection of *properties* (markup elements and
interfaces have attributes instead). Object objects are different from
Array objects. You have an Array object that holds references to Object
objects here, and you refer to that Array object by a variable named
`points' which (after assignment) holds a reference (value) to that object.
> I was thinking of using map, e.g.:
>
> var points = [{x: 1, y: 3}, {x: 2, y: 2}, {x: 3, y: 1}];
> alert(points.map(function(p){return p.x;}));
> alert(points.map(function(p){return p.y;}));
Actually, it is window.alert() (and thus should be called so), and it is no
longer part of the JavaScript language (since JavaScript 1.4) but provided
by a host-dependent API, the (Gecko) DOM. AFAWK, it has never been part of
Microsoft JScript or other ECMAScript implementations.
> JavaScript seems to be full of all sorts of neat tricks and I would be
> surprised if there wasn't a more standard way of doing this without
> resorting to loops.
Be surprised, then. The language standard is ECMAScript (currently Ed. 3)
and does not specify such a method. JavaScript is one of many (but probably
together with JScript one of the most prominent) ECMAScript implementations
and provides (in agreement with the standard's Conformance section) the
Array.prototype.map() method, but only since version 1.6 (Firefox 1.5+ and
other browsers that are based on the same or newer Gecko version).
Also since version 1.6, JavaScript provides the `for each' statement as part
of its support for ECMAScript for XML (E4X, ECMA-357). And as another
proprietary extension, JavaScript provides Array comprehensions since
version 1.7 (Firefox 2.0+ and Gecko compatibles). This can be combined into
[o.x for each (o in [{x: 1, y: 3}, {x: 2, y: 2}, {x: 3, y: 1}])]
However, this is still a loop, and far from being specified in a standard.
It is thus not supported by any version of Internet Explorer, Opera or
Safari yet, which again points out that there is not a single language but
several different ECMAScript implementations one has to deal with.
See also <http://PointedEars.de/es-matrix> for a (still incomplete) overview.
> Anyone have any ideas?
>
> N.B. I am using the following definition of map:
Understand that you only need that for compatibility in non-Geckos or older
Geckos (see above); therefore, it is preserved when defined (there):
> if (!Array.prototype.map)
> {
> Array.prototype.map = function(fun /*, thisp*/)
> [...]
However, that workaround employs too superficial a feature test. Search for
`isMethod' for a better one.
HTH
PointedEars