Skip to main content

Arrays

JavaScript arrays are objects that support storing properties indexed by integers. Neon exposes access to this class through the JsArray type.

Creating Arrays#

The easiest way to create a new array is through the Context::empty_array() method:

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

This is the equivalent of writing:

const a = [];

or

const a = new Array();

in JavaScript.

Indexed Properties#

You can get and set indexed properties of an array, i.e., properties with integer property keys, with the Object::get() and Object::set() methods:

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

This is equivalent to the JavaScript code:

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

Extending an Array#

The length of a JavaScript array is one more than its largest property index, which can be determined by calling the JsArray::len() method. You can extend the length of array by adding a property at that index:

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

This is equivalent to the JavaScript code:

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

Converting a Rust Vector to an Array#

An iterable Rust data structure such as Vec can be converted to a JavaScript array by looping over the elements. The JsArray::new() method can be used to preallocate enough capacity for the number of elements.

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 JavaScript Array to a Vector#

The JsArray::to_vec() method makes it easy to convert a JavaScript array to a Rust vector:

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