Arrays - jackbackrack/cons-beginners-course GitHub Wiki

Creating Arrays

  • [] -- var a = [] -- creates an empty array
  • [n m] -- var a = [n, m] -- creates an array with n and m

Getting Length of Array

  • a.length -- gets the length of array a

Accessing Elements

  • use a[i] syntax for accessing elements where a is an Array and i is an integer
  • offsets start at zero -- 0 corresponds to the 1st element and a.length - 1 is last element
const c = cube({ center: true });
const a = [c.translate([2, 0, 0]), c.translate([4, 0, 0]), c.translate([6, 0, 0])];
return a[0];

Accessing all elements

  • use the array as arguments -- union(a) unions all elements of a
const c = cube({ center: true });
const a = [c.translate([2, 0, 0]), c.translate([4, 0, 0]), c.translate([6, 0, 0])];
return union(a);

Adding to arrays

  • we can treat an array as a list of elements
  • push -- a.push(o) -- adds an element to the end of the array
const c = cube({ center: true });
const a = [];
a.push(c.translate([2, 0, 0]));
a.push(c.translate([4, 0, 0]));
return union(a);

Setting Elements

  • use a[i] = v syntax for setting elements where
    • a is an Array and i is an integer and v is a new value
var a = [33, 44];
a[0] = 99;
a == [99,44];

Homework

  • create an array of shapes and union them
  • create an array of two shapes and difference them with explicit array accesses
  • create an array of two shapes and swap them using element setting