Subj : Re: Iterating through all Array elements from C To : netscape.public.mozilla.jseng From : Matthew Mondor Date : Sat Feb 12 2005 01:08 pm This is a multi-part message in MIME format. --Multipart=_Sat__12_Feb_2005_13_08_42_-0500_ajOy1f9M5rNRZtn/ Content-Type: text/plain; charset=US-ASCII Content-Transfer-Encoding: 7bit On Thu, 10 Feb 2005 10:41:10 -0500 Matthew Mondor wrote: > Using SpiderMonkey, I have a static function of a class which requires > an array as a parameter. I can get the parameter, verify that it is > indeed an Array... However, I seem to have trouble to iterate though > all its elements, if the indexes are either non-contiguous or > non-numeric at initialization: I could make it work, creating an iterator function as attached. Unfortunately, I had to use JS_Enumerate() with an JSIdArray, which seems to be marked as being private API according to the reference docs. At least it solved my problem for now. Matt --Multipart=_Sat__12_Feb_2005_13_08_42_-0500_ajOy1f9M5rNRZtn/ Content-Type: text/plain; name="tmp.c" Content-Disposition: attachment; filename="tmp.c" Content-Transfer-Encoding: 7bit static JSBool object_iterate(JSContext *, JSObject *, void *, JSBool (*)(JSContext *, jsval *, jsval *, void *)); /* * Was written to be able to iterate over all elements of an array object, * despite being an associated array or not, or a mix of both. Unfortunately * uses marked as private JSIdArray structure. */ static JSBool object_iterate(JSContext *cx, JSObject *obj, void *udata, JSBool (*func)(JSContext *, jsval *, jsval *, void *)) { JSIdArray *a; jsval id, val; char *name; jsint i; JSBool ret = JS_FALSE; if ((a = JS_Enumerate(cx, obj)) != NULL) { for (i = 0; i < a->length; i++) { JS_IdToValue(cx, a->vector[i], &id); if (JSVAL_IS_STRING(id)) { /* * Property id is a string, attempt to * lookup its value by name. */ name = JS_GetStringBytes(JSVAL_TO_STRING(id)); if (!JS_LookupProperty(cx, obj, name, &val)) continue; } else { /* * Property id is a number, attempt to * lookup its array element by index. */ if (!JS_LookupElement(cx, obj, JSVAL_TO_INT(id), &val)) continue; } if (!(ret = func(cx, &id, &val, udata))) break; } JS_DestroyIdArray(cx, a); } return ret; } --Multipart=_Sat__12_Feb_2005_13_08_42_-0500_ajOy1f9M5rNRZtn/-- .