JeffLearnsReact – Arrays

Array methods – functions that manipulate array contents. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array let myArray = [‘item one’, ‘item two’, ‘item three’] const myArray = [‘item one’, ‘item two’, ‘item three’] if you use const, you cannot change the data type but you CAN manipulate the array in any way. Each item has a numbered position JS starts counting […]

Array methods – functions that manipulate array contents.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array

let myArray = [‘item one’, ‘item two’, ‘item three’]
const myArray = [‘item one’, ‘item two’, ‘item three’]

if you use const, you cannot change the data type but you CAN manipulate the array in any way.

Each item has a numbered position

JS starts counting from 0

myArray[0] gets the first item

get last item
var last = myArray[myArray.length – 1];

loop over array
myArray.forEach(function(item, index, array) {
console.log(item, index);
});

you can change the value of an item
myArray[0] = ‘first one’;

get the number of items with .length
myArray.length

add items to the beginning of the array with .unshift
myArray.unshift(‘item zero’)

add items to the end of the array with .push
myArray.push(‘item four’, ‘item five’);

remove the first item of an array with .shift
myArray.shift();

remove the last item of the array with .pop
myArray.pop();

get a section of items with .slice
myArray.slice(1,4); // 2nd thru 5th items

remove a section of items with .splice
myArray.splice(1,4) // removes items starting with 1 (the 2nd) and a total of 4 items // 2,3,4,5

NOTE: Strings are similar
let hello = ‘Hello World’;
console.log(hello[6]); // Output: W

Powered by WPeMatico