Skip to content

Arrays

Fresh 🌱

JavaScript arrays are objects that store properties indexed by integers. Neon exposes them through the JsArray type.

Creating arrays

The easiest way to create a new array is cx.empty_array():

rust
let a: Handle<JsArray> = cx.empty_array();

This is the equivalent of const a = [] (or new Array()) in JavaScript.

Indexed properties

Get and set integer-keyed properties with Object::get() and Object::set():

rust
let a = cx.empty_array();

let s = cx.string("hello!");
a.set(&mut cx, 0, s)?;

let v = a.get(&mut cx, 1)?;

Equivalent JavaScript:

javascript
const a = [];
const s = "hello!";
a[0] = s;
const v = a[1];

Extending an array

A JavaScript array's length is one more than its largest property index. Read it with JsArray::len(), and append by setting a property at that index:

rust
let len = array.len(&mut cx)?;
array.set(&mut cx, len, value)?;

Equivalent JavaScript:

javascript
const len = array.length;
array[len] = value;

Converting a Rust Vec to a JS array

Loop over an iterable Rust structure and set each element. JsArray::new() preallocates capacity:

rust
fn vec_to_array<'a, C: Context<'a>>(vec: &Vec<String>, cx: &mut C) -> JsResult<'a, JsArray> {
    let a = JsArray::new(cx, vec.len() as u32);

    for (i, s) in vec.iter().enumerate() {
        let v = cx.string(s);
        a.set(cx, i as u32, v)?;
    }

    Ok(a)
}

Converting a JS array to a Rust Vec

JsArray::to_vec() does the reverse in one call:

rust
let vec: Vec<Handle<JsValue>> = arr.to_vec(&mut cx);

Arrays are objects

Because JsArray implements Object, everything you know about object properties applies - get/set work with both string keys and integer indices.

For raw binary data (not general JS values), reach for Buffers & Typed Arrays instead, which give you zero-copy slices.