Friday, March 30, 2018

Array concat method

concat method joins the array with other arrays and/or items.

The syntax is:

arr.concat(arg1, arg2...)

Explanation:

The arguments could either arrays or values. After concat the result is a new array containing items from arr, then arg1, arg2 etc.

Below is very basic example for concat.



let arr = [1, 2];

// merge arr with [3,4]
alert( arr.concat([3, 4])); // 1,2,3,4

// merge arr with [3,4] and [5,6]
alert( arr.concat([3, 4], [5, 6])); // 1,2,3,4,5,6

// merge arr with [3,4], then add values 5 and 6
alert( arr.concat([3, 4], 5, 6)); // 1,2,3,4,5,6


Adding objects is little different. It will add as a whole. Let see a example,


let arr = [1, 2];

let arrayObject = {
  0: "something",
  length: 1
};

alert( arr.concat(arrayLike) ); // 1,2,[object Object]
//[1, 2, arrayObject]







No comments:

Post a Comment