Javascript Array concat() method

Description

Javascript Array concat() method



Array.prototype.concat = function(){
 var result = [];
 this.forEach(function(subArray){
  result.push.apply(result, subArray);//  w  w w.  j  a  v  a2s. c  o  m
 });
 return result;
}

var a = [[2,3,4,5],[11,2,333],[33,232,21]];
a.concat();


var a = [1,22,34,4,66];
Math.max.apply(null,a); // works beacuse it gives it as a[0],a[1] etc
but Math.max.call(null,a) // NaN. Because call cannot split it as a[0],a[1], hence a is intrepreted as whoe array and Not a Number

Javascript Array concat()



Array.prototype.concat = function() {
 let newArr = Array.prototype.slice.call(this);
 let args = Array.prototype.slice.call(arguments);
 for(let i = 0, len = args.length; i < len; i++){
  if(Array.isArray(args[i])){
   for(let j = 0, len = args[i].length; j < len; j++){
    newArr.push(args[i][j]);//from  w  w  w. j a  va 2 s .c o m
   }
  }else{
   newArr.push(args[i]);
  }
 }

 return newArr;
}



PreviousNext

Related