xxxxxxxxxx
var ar = ['one', 'two', 'three'];
ar[3] = 'four'; // add new element to ar
xxxxxxxxxx
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']
xxxxxxxxxx
// use of .push() on an array
// define array
let numbers = [1, 2]
// using .push()
numbers.push(3) // adds the value 3 to the end of the list
console.log(numbers) // [1, 2, 3]
xxxxxxxxxx
// Add to the end of array
let colors = ["white","blue"];
colors.push("red");
// ['white','blue','red']
// Add to the beggining of array
let colors = ["white","blue"];
colors.unshift("red");
// ['red','white','blue']
// Adding with spread operator
let colors = ["white","blue"];
colors = [colors, "red"];
// ['white','blue','red']
xxxxxxxxxx
var arrayExample = [53,'Hello World!'];
console.log(arrayExample) //Output =>
[53,'Hello World!']
//You can also do this
arrayExample.push(true);
console.log(arrayExample); //Output =>
[53,'Hello World!',true];
xxxxxxxxxx
#include <vector>
#include <iostream>
int main() {
std::vector<int> v;
v.push_back(42);
std::cout << v.size() << "\n";
std::cout << v.back() << "\n";
}
Output:
1
42