Forms a legitimate JavaScript array from an array-like object - Node.js Array

Node.js examples for Array:Array Value

Description

Forms a legitimate JavaScript array from an array-like object

Demo Code


/**//from  www .j  a  va2  s .  c  om
 * Forms a legitimate JavaScript array from an array-like object
 * (eg NodeList objects, function argument lists).
 */
Util.Array.from = function array_from_iterable(iterable)
{
  if (!iterable)
    return [];
  if (iterable.toArray)
    return iterable.toArray();
  
  try {
    return Array.prototype.slice.call(iterable, 0);
  } catch (e) {
    // This doesn't work in Internet Explorer with iterables that are not
    // real JavaScript objects. But we still want to keep around the slice
    // version for performance on Gecko.
    
    var new_array = [];
    for (var i = 0; i < iterable.length; i++) {
      new_array.push(iterable[i]);
    }
    
    return new_array;
  }
  
};

Related Tutorials