Javascript Array first(n)

Description

Javascript Array first(n)


/*/*from   www . ja va2s . co m*/
    Return first n set of elements in an array
*/

Array.prototype.first = function (n) {
    'use strict';
    return this.slice(0, n || 1);
};

Javascript Array first(n)

// Returns the first element of an array.
// Passing n will return the first n elements of the array.

var array = [5, 4, 3, 2, 1];

Array.prototype._first = function(n){
  n = n || 1;//w w w.  ja  v  a 2  s  . c  o m
  return this.slice(0, n);
};

array._first();
// [5]

array._first(3);
// [5, 4, 3]



PreviousNext

Related