На прошлой неделе я закончил разделы по чистому JavaScript и начал переходить к миру DOM. Давайте выделим те темы, которые были рассмотрены!
Темы из раздела 22
Следующие несколько тем посвящены встроенным методам массивов, которые требуют от нас передачи функций. Это важная часть работы с массивами в JavaScript, а массивы имеют решающее значение для работы с JavaScript, поэтому тема очень важна.
- For Each: Принимает функцию обратного вызова. Вызывает функцию один раз для каждого элемента массива. Они также устарели, и в некоторых случаях их можно заменить более новым синтаксисом.
const numbers = [9, 8, 7, 6, 5, 4, 3, 2, 1];
//We are passing an in-line function, though we could define a
//function outside of the forEach and instead plug in the
//function name
numbers.forEach(function(n){
console.log(n * n)
//Prints: 81, 64, 49, 36, 25, 16, 9, 4, 1
});
- Map: Создает новый массив с результатами вызова обратного вызова для каждого элемента массива. Работает так же, как forEach, но затем создает новый массив на основе результата.
const movies = [
{
title: ""Toy Story","
score: 92
},
{
title: ""Stand By Me","
score: 85
},
{
title: ""Soul","
score: 95
},
{
title: ""Avengers: End Game","
score: 94
},
{
title: ""Finding Nemo","
score: 86
},
];
//Creates a new array called "titles" pulling from the movies array
const titles = movies.map(function(movie){
return movie.title;
})
-
Функции стрелок: Позволяет нам писать функции без использования ключевого слова «function».
-
setTimeout и setInterval: Две функции, которые ожидают, что вы передадите функцию обратного вызова, но не являются методами массива. Они задерживают/откладывают выполнение кода на
более позднее время.
//setTimeout-----------------------------------------------
//runs and prints 1st
console.log("Hello!")
//This will run just one time, and will print 3rd
setTimeout(function(){
console.log("I waited 3 seconds...");
}, 3000)
//this runs 3rd but will print out 2nd because setTimeout is on a
//3 second delay
console.log("Last coded console.log message!")
//setInterval-----------------------------------------------
//Using an arrow function this time, doesn't matter but is shorter
//Will run forever every two seconds
//We set this to a variable so we can call clearInterval(id)
const id = setInterval(() =>{
console.log(Math.random());
}, 2000)
- Метод фильтра: Создает новый массив со всеми элементами, которые проходят тест, реализованный предоставленной функцией. Обычно мы передаем функцию, которая должна возвращать true или false, и любой элемент, который возвращает true, добавляется в новый созданный отфильтрованный массив.
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
const odds = numbers.filter(n => {
return n % 2 === 1;
//Our callback returns true or false, if true n is added to the filtered array
})
//Will return [1, 3, 5, 7, 9]
const smallNumbers = numbers.filter(n => n < 5);
//will return [1, 2, 3, 4]
-
Some и Every: Some возвращает true, если любой из элементов массива проходит функцию проверки. Every проверяет, все ли элементы массива проходят функцию проверки, и если да, то возвращает true.
-
Reduce: Выполняет функцию метода reducer над каждым элементом массива, в результате чего получается одно значение. Это может быть математический метод, а также сравнение значений, которые могут находиться в массиве или быть частью объекта.
[3, 5, 7, 9, 11].reduce((accumulator, currentValue) =>{
return accumulator + currentValue;
});
//The final return value for this will be 35
Темы из раздела 23
- Параметры по умолчанию: При создании функции можно по желанию попросить пользователя ввести значение, а если он этого не сделает, то использовать значение по умолчанию (параметр).
//We've set this function's default params so that if the user
//doesn't input a value when calling rollDie() then it will
//use 6 as the default for numSides
function rollDie(numSides = 6){
return Math.floor(Math.random() * numSides) +1;
}
- «Разброс» в вызовах функций: Это своего рода армейский нож JavaScript. Мы берем что-то и расширяем или раздвигаем» это (массив, строку и т.д.).
const nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
//To use Math.max we need to "spread" the array of numbers into individual values so the function can find the maximum value
//We use ... before calling the nums array to "spread" the values inside the nums array
//Spread creates the seperate arguments (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15) from the nums array and then
//executes the .max() function with those arguments
console.log(`The maximum number is: ${Math.max(...nums)}`);
- «Распространение» с помощью литералов массива: Создайте новый массив, используя существующий массив. Распространяет элементы из одного массива в другой.
const cats = ["Ella", "Tommy", "Buddy"];
const dogs = ["Daisy", "Piston"];
//We are spreading the two arrays into a new array
const allPets = [...cats, ...dogs];
console.log(allPets);
- «Spread» With Object Literals: Копирует свойства из одного объекта в другой объект. Часто используется при копировании объектов.
//A real world example, a user signs up for our website and we want to copy their input and add data of our own
const dataFromform = {
email: "fake@gmail.com",
username: "SirFaketon",
password: "fakepassword123"
}
//Now lets add data to their input
const newUser = {...dataFromform, id: 12345, isAdmin: false}
- Rest Params: Синтаксис выглядит как разброс, но это не так, мы не разбрасываем вещи, а собираем их в один параметр. Собирает все оставшиеся аргументы, не вызванные специально, в собственный массив.
function raceResults(gold, silver, ...everyoneElse){
console.log(`Gold medal goes to: ${gold}`);
console.log(`Silver medal goes to: ${silver}`);
console.log(`And thanks to everyone else for participating: ${everyoneElse}`);
console.log(raceResults("Ethan", "Dan", "Tim", "Ashley"));
}
- Деструктуризация массивов: Короткий, чистый синтаксис для «распаковки» значений из массивов и свойств из объектов в отдельные переменные.
const pinballScores = [984537, 912385, 872357, 817490, 817245, 726349, 613279];
//With this we are making 3 variables (gold, silver, and bronze)
//and the order of the array determines what values they are
//Gold will be index 0, silver will be index 1, and bronze will be index 2
//The [] indicate we are destructing from an array
//Also we are using the ... or "rest" parameter to define the rest of the scores
const [gold, silver, bronze, ...everyoneElse] = pinballScores;
console.log(`Gold score is: ${gold}`);
console.log(`Silver score is: ${silver}`);
console.log(`Bronze score is: ${bronze}`);
console.log(`Runner up scores are: ${everyoneElse}`);
- Деструктуризация объектов: Деструктуризация чаще всего используется с объектами, поскольку в этом случае не учитывается порядок элементов, а вместо этого рассматривается их свойство «ключ-значение». Пример: {name: Ethan} вместо того, чтобы искать индекс 0 массива. Это никак не изменяет исходный объект.
//An exmaple of destructing an object
const runner = {
firstName: "Eliud",
lastName: "Kipchoge",
country: "Kenya",
title: "Elder of the Order of the Golden Heart of Kenya"
}
const {firstName, lastName, country} = runner;
console.log(`The winner of the race is ${firstName} ${lastName} from ${country}!`);
- Уничтожение параметров: Наиболее часто используется с объектами, мы можем деструктурировать значения, передаваемые в функцию.
const user1 = {
email: "stacy@gmail.com",
firstName: "Stacy",
lastName: "LaPreaze",
born: 1975,
city: "Morley",
state: "Michigan"
}
const user2 = {
email: "george@gmail.com",
firstName: "George",
lastName: "Windfall",
born: 1935,
died: 1987,
city: "Morley",
state: "Michigan",
occupation: "Systems Engineer"
}
//Destructure and only grab firstName and lastName. Also setting a
//default value (param) in case there's no info, but this is
//totally optional
function fullName({firstName = "Missing Value", lastName = "Missing Value"}){
return `${firstName} ${lastName}`;
}
Обзор недели
Что ж, это был большой объем работы за неделю, но я добился большого прогресса и рад наконец-то начать объединять HTML/CSS/JavaScript в нечто пригодное для использования. Следующий этап — мир DOM!
Пройденные уроки Bootcamp: 244/579
Надеюсь, вам понравилось!
Не стесняйтесь следить за мной на GitHub, LinkedIn и DEV, чтобы узнать больше!