const f1 = function() {
console.log("I am F 1");
};
const f2 = f1;
f2(); // I am F 1
function call_if_true(value, func) {
if (value) {
func();
}
}
call_if_true(
1,
function() { console.log("It's true!"); }
);
const students = [
{ name: 'One', marks: [8, 10, 7, 5, 4] },
{ name: 'Two', marks: [5, 2, 8, 5, 3] },
{ name: 'Three', marks: [6, 9, 3, 6, 7] },
{ name: 'Fore', marks: [1, 7, 8, 4, 10] },
{ name: 'Five', marks: [5, 8, 6, 9, 3] },
];
const min = { student: null, avg: Number.POSITIVE_INFINITY };
const max = { student: null, avg: Number.NEGATIVE_INFINITY };
students.forEach(student => {
const { marks } = student;
const avg = marks.reduce((acc, c) => acc + c) / marks.length;
if (avg > max.avg) {
max.avg = avg;
max.student = student;
} else if (avg < min.avg) {
min.avg = avg;
min.student = student;
}
});
console.log('Student with mininal average mark', min.student);
console.log('Student with best average mark', max.student);
location.hash
соотв. хэш.const news = (new URL(document.location)).searchParams.get('news');
if (news) document.location.hash = news;
input
, а сбоку от него, именно на div
'е, то порядок событий такой же как во втором. Как вешали обработчики, в том же порядке отрабатывают: 1, 2.div
со слушателями, то 2-й сработает первым, ещё на фазе «погружения» события, т.к. у второго слушателя третьим аргументом true
. for (let key in objectEmployee) {
что будет в key?objectEmployee.key['age']
есть ли у objectEmployee
свойство key
? (нет)const filters = {
age: v => v >= 25,
education: v => v === 'higher',
experience: v => v >= 1,
};
const employee = {};
const defaultDescriptor = { writable: true, enumerable: true, configurable: true };
Object.defineProperties(employee, {
name: { ...defaultDescriptor, value: 'Dmitriy', writable: false },
age: { ...defaultDescriptor, value: 21 },
education: { ...defaultDescriptor, value: 'higher' },
experience: { ...defaultDescriptor, value: 0 },
});
const hireNewEmployee = (employee, filters) => {
const errors = [];
Object.entries(filters).forEach(([name, func]) => {
if (!func(employee[name])) {
errors.push(name);
}
});
return errors.length
? `Not hired: sorry we cannot hire you. Here is why: ${errors.join(', ')}`
: 'You are Hired! Congrats!';
};
hireNewEmployee(employee, filters);
// "Not hired: sorry we cannot hire you. Here is why: age, experience"
async..await
равносильно throw
catch
.v.0.22.0
event.target
– это кликнутый элемент.document.addEventListener('click', ({ target }) => {
if (!target.classList.contains('button')) return; // не тот клик
target.classList.toggle('active');
});
const isEmpty = obj => Object.keys(obj).length <= 2;
console.log( isEmpty({ a: "AAA" }) ? 'object is empty' : 'object is full of properties' );
// выведет "object is empty"
console.log( isEmpty({ a: "AAA", b: "BB", c: "C" }) ? 'object is empty' : 'object is full of properties' );
// выведет "object is full of properties"
<span class="animals" data-allowed="{{$cabin->HasAnimals}}">
{{$cabin->HasAnimals?Translate::GetTranslation('Animals Allowed'):Translate::GetTranslation('Animals Not Allowed')}}
</span>
const span = document.querySelector('span.animals');
const isAnimalsAllowed = !!span.dataset.allowed;
span
бэк отрисовываетid
– видимо, массив.id.length
– длина массива. Например, для массива [7, 7, 7]
длина 3.id.length - 1
– индекс последнего элемента в массиве. Индексы считаются от 0.id
. И из него вытаскивают его свойство default
.` text ${ js_expression } `
почитайте про строки в обратных кавычках и интерполяцию выражений в них.const word = "мир";
`Привет, ${ word }!` // "Привет, мир!"
fetch()
. Устанавливается соединение, передаётся запрос «дай /api/method» и передаются заголовки, типа «готов принять json».HTTP/1.1 200 OK
– мол, норм, ща всё будет.fetch
уже понимает, как у него дела с этим запросом. И ресолвит первый промис. Уже ясно, что вроде всё ок, ща польют данные, и это надолго. Дальше вступает в работу объект Response..json()
промис. Посмотрите по ссылке — у того же объекта (мы его получаем после первого ресолва fetch()
) есть и свойства, доступные сразу же, синхронно: например, объект с заголовками: свойство headers
. Или свойство ok
, значение которого следует из самой первой строки ответа сервера.this
.logger()
в вашем примере, this === window
.randNum
содержит число.questFunc()
возвращает строку с текстом вопроса.people[`${questFunc()}`]
это, например, people["Это девушка?"]
– будет undefined
.people
не имеет строкового ключа. В нём два элемента с индексами 0 и 1.const questions = [
'Это самец?',
'Это девушка?',
'Носит очки?',
'Занимается спортом?',
'У этого человека смуглая кожа?',
];
const people = [
{ name: 'Егор', profile: [1, 0, 1, 1, 1] },
{ name: 'Залина', profile: [0, 1, 1, 1, 0] },
];
const questionElement = document.querySelector('.question');
let questionIndex; // индекс текущего вопроса
function askQustion() {
questionIndex = Math.floor(Math.random() * questions.length);
questionElement.innerHTML = questions[questionIndex];
return questions[questionIndex];
}
askQustion();
// TODO: принять ответ пользователя (true/false)
const answer = true; // допустим, ответил "да"
const candidates = people
.filter(({ profile }) => !!profile[questionIndex] === answer)
.map(({ name }) => name)
.join(', ');
console.log('Кандидаты:', candidates);
#container
, а MutationObserver это замечает и пишет в #log
: