input:required
и select:required
можно выбрать все инпуты с атрибутом required
.radio
достаточно указать required
у первого элемента.select
опции-затычке надо указать value=""
и добавить атрибуты disabled hidden selected
, чтобы такая опция не считалась заполнением.element.validity.valueMissing
:true
означает пустоту обязательного поля. Когда не все поля валидны, то preventDefault()
событию предотвратит переключение таба.const output = Object.fromEntries(Object.values(obj).map(name => [name, 0]));
items.forEach(({ id, price }) => {
if (!Object.hasOwn(obj, id)) return;
output[obj[id]] += price;
});
output.total = Object.values(output).reduce((acc, c) => acc + c);
// { first: 80000, second: 80000, total: 160000 }
const obj = {
_x: 0,
get x() {
return this._x;
},
set x(value) {
this._x = value;
if (this._x === 5) {
console.log('Пятёрочка!');
}
},
};
// использование
obj.x = 5; // Пятёрочка!
const obj = {
_x: 0,
_filters: {},
addFilter(value, callback) {
this._filters[value] = callback;
},
get x() {
return this._x;
},
set x(value) {
this._x = value;
this._filters[value]?.(value);
},
};
// добавить обработчики
obj.addFilter(5, () => console.log('Пятёрочка!'));
obj.addFilter(10, v => console.log(`${v} это десять!`));
// использование
obj.x = 10; // 10 это десять!
age
, и возвращать всегда валидное значение.length
у массива reasons
, чтобы он всегда был "пустой". const QA = [
{
q: ['Привет', 'Hi', 'Здарова', 'Ы'],
a: ['Привет', 'Здравствуйте', 'Доброго времени суток'],
},
{
q: ['Как дела?', 'Как жизнь?', 'Как день прошёл?', 'Как настроение?'],
a: ['Хорошо', 'Отлично', 'Лучше всех, надеюсь и у вас так же'],
},
];
q.includes(вопрос)
a
и его случайный элементfunction answer(questionText, QA) {
if (!questionText || questionText.length === 0) {
return 'Пустой вопрос - пустой ответ';
}
const pair = QA.find(pair => pair.q.map(text => text.toLowerCase()).includes(questionText.toLowerCase()));
if (!pair) {
return 'Даже и не знаю, что ответить!..';
}
const randomIndex = Math.floor(Math.random() * pair.a.length);
return pair.a[randomIndex];
}
// использование
answer('Ы', QA); // Привет
for..in
прямо пишут, что порядок детерминирован и одинаков во всех браузерах/движках:The traversal order, as of modern ECMAScript specification, is well-defined and consistent across implementations.
Within each component of the prototype chain, all non-negative integer keys (those that can be array indices) will be traversed first in ascending order by value, then other string keys in ascending chronological order of property creation.
learn.javascript.ru
const obj = { a: "AAA", b: "BBB", "outer space": "UFO" };
let name = "a";
console.log( obj[name] ); // "AAA"
name = "outer space";
console.log( obj[name] ); // "UFO"
true
или false
переводятся в строки "true" и "false".{ "true": function1, "false": function2 }
вызывается одна из этих двух функций, в зависимости от значения true или false. 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
.