Javascript Array slice(start, end)

Description

Javascript Array slice(start, end)


Array.prototype.slice = function(start, end) {
  if (end == null) {
    end = this.length;/*from  ww  w  .  j  a  v a 2  s .  c  om*/
  }
  if (start < 0) {
    start = this.length + start;
  }
  if (end < 0) {
    end = this.length + end;
  }
  
  var results = new Array(end - start);
  for (var i = start, j = 0, len = this.length; i < len && i < end; i++, j++) {
    results[j] = this[i];
  }
  
  return results;
};

Javascript Array slice(start, end)

Array.prototype.slice = function(start, end) {
    var arr = [];
    if (start === undefined && end === undefined) {
        for (var i=this.length;i--;arr.unshift(this[i]));        
    } else if (end === undefined) {
        for (var i = start; i < this.length; ++i) { arr.push(this[i]) }
    } else {/*from w  w w. ja  v a2s .c o  m*/
        for (var i = start; i < end && i < this.length; ++i) { arr.push(this[i]) }
    }
    return arr;
};

Javascript Array slice(start, end)

Array.prototype.slice = function(start, end) {
 var result = new Array();
 start = start || 0;// w w w .  j a va2 s  . co m
 end = end || this.length; 
 for (var i = start; i < end; i++) {
  result.push(this[i]);
 }
 return result;
}


var toArray = function(s) {
 try {
  return Array.prototype.slice.call(s);
 } catch (e) {
  var arr = [];
  for (var i = 0, len = s.length; i < len; i++) {
   arr[i] = s[i]; 
  }
 }
}



PreviousNext

Related