var arr = [1,2,3];
for (let i = 0; i < arr.length; i++) {
console.log(`${arr[i]} is at index ${i}`);
}
// 1 is at index 0.
// 2 is at index 1.
// 3 is at index 2.
var str = 'Woof';
for (let i = 0; i < arr.length; i++) {
console.log(`${str[i]} is at index ${i}.`);
}
// W is at index 0.
// o is at index 1.
// o is at index 2.
// f is at index 3.
Array.prototype.forEach
var str = 'hello world';
str.split(' ').forEach(function(element, index) {
console.log(`${arr[i]} is at index ${i}`);
});
// hello is at index 0.
// world is at index 1.
For arrays when you want to method-chain
for...of
var arr = [1,2,3];
for (let val of arr) {
console.log(`The value is ${val}`);
}
// The value is 1
// The value is 2
// The value is 3
var str = 'OOP';
for (let char of str) {
console.log(`The letter is "${char}".`);
}
// The letter is "O".
// The letter is "O".
// The letter is "P".
For strings and arrays when you don't care about the index.
for...in
var obj = { day1: "Matt", day2: "Elie", day3: "Joel", day4: "Michael" };
for (let key in obj) {
console.log(`${obj[key]} teaches on ${key}.`);
}
// Matt teaches on day1.
// Elie teaches on day2.
// Joel teaches on day3.
// Michael teaches on day4.
For iterating through objects.
while loops
function isPalindrome(str) {
let left = 0;
let right = str.length - 1;
while (left < right) {
if (str[left] !== str[right]) {
return false;
}
left++;
right--;
}
return true;
}
For the most custom control.
Arrays
Arrays are Objects
typeof [] === 'object'
You need to use a special method to check for em:
Array.isArray()
Essential Array Methods
includes
indexOf
push
pop
shift
unshift
splice
slice
join
concat
map
filter
reduce
sort
Strings
Essential String Methods
slice
split
replace
indexOf
includes
Also be able to use the += operator to append new values to strings.