Q:

js add function to array

var colors=["red","white"];
colors.push("blue");//append 'blue' to colors
79
array.push(element)
27
const myArray = ['hello', 'world'];

// add an element to the end of the array
myArray.push('foo'); // ['hello', 'world', 'foo']

// add an element to the front of the array
myArray.unshift('bar'); // ['bar', 'hello', 'world', 'foo']

// add an element at an index of your choice
// the first value is the index you want to add at
// the second value is how many you want to delete (0 in this case)
// the third value is the value you want to insert
myArray.splice(2, 0, 'there'); // ['bar', 'hello', 'there', 'world', 'foo']
2
//create an new function that can be used by any array
Array.prototype.second = function() {
  return this[1];
};

var myArray = ["item1","item2","item3"];
console.log(myArray.second());//returns 'item2'
1

New to Communities?

Join the community