JS_NewArrayObject

This article is in need of a technical review.

Create a new Array object.

Syntax

JSObject *
JS_NewArrayObject(JSContext *cx, const JS::HandleValueArray& contents); // Added in SpiderMonkey 31

JSObject *
JS_NewArrayObject(JSContext *cx, size_t length); // Added in SpiderMonkey 31

JSObject *
JS_NewArrayObject(JSContext *cx, int length, jsval *vector); // Obsolete since JSAPI 30
Name Type Description
cx JSContext * The context in which to create the new array. Requires request. In a JS_THREADSAFE build, the caller must be in a request on this JSContext.
contents JS::HandleValueArray& Reference to the initial values for the array's elements. Added in SpiderMonkey 31
length size_t or int The length of the new array. This must not be negative.
vector jsval * Pointer to the initial values for the array's elements, or NULL. Obsolete since JSAPI 30

Description

JS_NewArrayObject with contents parameter creates a new array object with the specified contents elements. JS_NewArrayObject defines an enumerable array element with the value contents[i] on the new array.

JS_NewArrayObject with length parameter creates a new array object with the specified length; the result is like the JavaScript expression new Array(length). The new array has the specified length, but it doesn't have any elements.

On success, JS_NewArrayObject returns the new array object. Otherwise it reports an error as though by calling JS_ReportOutOfMemory and returns NULL.

Obsolete since JSAPI 30.

JS_NewArrayObject with length parameter creates a new array object with the specified length. If vector is non-null, then for each index i from 0 to length - 1, JS_NewArrayObject defines an enumerable array element with the value vector[i] on the new array. (This means that if length is nonzero and vector is null, the result is like the JavaScript expression new Array(length). The new array has the specified length, but it doesn't have any elements.)

It is often better to call JS_NewArrayObject(cx, 0, NULL), store the returned object in a GC root, and then populate its elements with JS_SetElement or JS_DefineElement. This avoids unrooted jsvals in vector from being subject to garbage collection until the new object has been populated.

See Also

Document Tags and Contributors

Contributors to this page: kscarfone, arai, fscholz, Jorend, Dria, MMondor
Last updated by: kscarfone,
Hide Sidebar