Array.cast >= 0.1.0

Purpose

Cast a variable to an array

Description

Also turns array-like objects into real arrays, except String objects.

Do not use it on 'arguments' (see example below)

Syntax

Array.cast ( variable );

Parameters

variable

The variable to cast to an array

Return values

Array

Examples

Encasing primitive variables

// A number
Array.cast(1);
>>> [1]

// A string (even though it has a `length` property)
Array.cast("test");
>>> ["test"]

// A boolean
Array.cast(true);
>>> [true]

Encasing plain objects

// An empty object
Array.cast({});
>>> [{}]

// A filled in object
Array.cast({key: 'val'});
>>> [{key: 'val'}]

// An object with numeric keys
Array.cast({'1': 'a', '2': 'b'});
>>> [{'1': 'a', '2': 'b'}]

Casting array-like objects

Array-like objects have numeric keys and a length property

// Construct an array-like object
var obj = {
    '0': 'a',
    '1': 'b',
    '2': 'c',
    length: 3
};

Array.cast(obj);
>>> ["a", "b", "c"]

The length property is important and will be honoured

// Array-like object with a different length than number of properties
var obj = {
    '0': 'a',
    '1': 'b',
    '2': 'c',
    length: 1
};

Array.cast(obj);
>>> ["a"]

A length longer than the amount of key-value pairs will result in undefined slots

// Array-like object with a longer length than number of properties
var obj = {
    '0': 'a',
    length: 3
};

Array.cast(obj);
>>> ["a", undefined, undefined]

Encasing a String instance

Even though a "new String()" instance is an object, has numeric keys and has a length, it will not be converted to an array

Array.cast(new String('test'));
>>> [String]

Turning arguments into an array (don't do this!)

You can use Array.cast() to turn the 'arguments' object into an array, but you really should not do this.

It'll leak the arguments object out of your function, and the function won't get optimized.

You should ALWAYS use a for-loop to turn arguments into an array. I promise you it's faster.

Hell: it's even faster when you just want to pass the arguments object to another function.

// Keep function optimized by not leaking the `arguments` object
var args = new Array(arguments.length);
for (var i = 0; i < args.length; i++) args[i] = arguments[i];

Comments