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 равносильно throwcatch.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:const nodes = [ ...document.querySelector('td').childNodes ];
const index = nodes.findIndex(({ nodeName }) => nodeName === 'BR');
if (index > -1) nodes[index + 1].remove();Находим все узлы DOM внутри td. Их будет 3:sort() изменяет сам массив.myFunction() без второго аргумента, возвращается массив как есть. Как отсортировали его предыдущим вызовом.function myFunction(arr, str) {
const sortedArray = arr.slice(); // копия, чтобы не менять оригинал
if (str === 'asc') {
sortedArray.sort((a, b) => a - b);
} else if (str === 'dsc') {
sortedArray.sort((a, b) => b - a);
}
return sortedArray;
}
console.log(myFunction([1, 4, 3, 2], 'asc')); // [ 1, 2, 3, 4 ]
console.log(myFunction([1, 4, 3, 2], 'dsc')); // [ 4, 3, 2, 1 ]
console.log(myFunction([1, 4, 3, 2])); // [ 1, 4, 3, 2 ] без изменений last (не знаю, откуда взялось last_price)function handleFiles(files) {
for (let i = 0; i < files.length; i++) {
const file = files[i];
if (!file.type.startsWith('image/')){ continue }
const img = document.createElement("img");
img.classList.add("obj");
img.file = file;
preview.appendChild(img); // Assuming that "preview" is the div output where the content will be displayed.
const reader = new FileReader();
reader.onload = (e) => { img.src = e.target.result; };
reader.readAsDataURL(file);
}
}