let dailyActivities =['eat','sleep'];// add an element at the end
dailyActivities.push('exercise');console.log(dailyActivities);// ['eat', 'sleep', 'exercise']
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']
//adding items to array
objects =[];
objects.push("you can add a string,number,boolean,etc");//if you more stuff in a array//before i made a error doing value = : value
objects.push({variable1: value,variable2: value);//we do the {} so we tell it it will have more stuff and the variable : value
// use of .push() on an array// define arraylet numbers =[1,2]// using .push()
numbers.push(3)// adds the value 3 to the end of the listconsole.log(numbers)// [1, 2, 3]
// Add to the end of arraylet colors =["white","blue"];
colors.push("red");// ['white','blue','red']// Add to the beggining of arraylet colors =["white","blue"];
colors.unshift("red");// ['red','white','blue']// Adding with spread operatorlet colors =["white","blue"];
colors =[...colors,"red"];// ['white','blue','red']
// To merge two or more arrays you shuld use concat() method.const array1 =['a','b','c'];const array2 =['d','e','f'];const array3 = array1.concat(array2);console.log(array3);// expected output: Array ["a", "b", "c", "d", "e", "f"]
how to append an element to an array in javascript
//Use push() method//Syntax:
array_name.push(element);//Example: let fruits =["Mango","Apple"];//We want to append "Orange" to the array so we will use push() method
fruits.push("Orange");//There we go, we have successfully appended "Orange" to fruits array!
let array =["Chicago","Los Angeles","Calgary","Seattle",]// print the array console.log(array)//Adding a new item in an array without touching the actual array
array.push('New Item')< variable_name >.push(<What you want to add >)//How many items does the array have?console.log("This array has", array.length,"things in it")