Есть ли что-то типо delegate() для такого случая?
В результирующем массиве значения исходного массива с числовыми ключами будут перенумерованы в возрастающем порядке, начиная с нуля.
$result = $array1 + $array2;
рейтинг для каждой книги - COUNT записей
SELECT b.*, COALESCE(SUM(br.rating), 0) rating
FROM books b
LEFT JOIN books_rating br ON br.book_id = b.id
GROUP BY b.id
можно открыть в конце концов build.js и увидеть там...
Консоль говорит, что не может найти product, потому что я не правильно использую хуки.
var prod = product;product? Это который в data лежит? Тогда должно быть this.product. Почему вы пытаетесь определить переменную с таким же именем как и у параметра? А при вызове в хуке mounted - почему ничего не передаёте в метод results, у него же определён параметр?mounted при вызове results передавайте ему product - this.results(this.product). Или так: строку удаляете, удаляете параметр prod, в вызове axios.get вместо prod используете this.product.
const days = ['Понедельник', 'Вторник', 'Среда', 'Четверг', 'Пятница', 'Суббота', 'Воскресенье'];
// или
const days = Array.from({ length: 7 }, (_, i) => new Date(1, 0, i)
.toLocaleString('ru', { weekday: 'long' })
.replace(/./, m => m.toUpperCase()
));for (
let iDay = 0;
confirm(`${days[iDay]}. Хотите увидеть следующий день?`);
iDay = (iDay + 1) % days.length
) ;
сделал это так, но мне кажется, это не совсем производительно и есть решение получше
const lastId = arr.reduce((id, n) => n.glob_id || id, null);
// или
const lastId = (arr.filter(n => n.glob_id).pop() || {}).glob_id;
// или
const lastId = ([...arr].reverse().find(n => n.glob_id) || {}).glob_id;
// или
const lastId = arr.map(n => n.glob_id).filter(Boolean).pop();let lastId = null;
for (let i = arr.length; i--;) {
if (arr[i].glob_id) {
lastId = arr[i].glob_id;
break;
}
}const lastId = arr.findLast(n => n.glob_id)?.glob_id;
<div id="map" class="black-and-white"></div>.black-and-white {
filter: grayscale(100%);
}document.querySelector('#map').addEventListener('click', function() {
this.classList.remove('black-and-white');
}, { once: true });
const parentSelector = 'div';
const childSelector = 'p';
const className = 'there';
const siblingsSelector = `${parentSelector} > ${childSelector}`;
const elementSelector = `${siblingsSelector}.${className}`;const index = Array.prototype.findIndex.call(
document.querySelectorAll(siblingsSelector),
n => n.classList.contains(className)
);let index = -1;
for (
let el = document.querySelector(elementSelector);
el;
index++, el = el.previousElementSibling
) ;const el = document.querySelector(elementSelector);
const index = el ? [...el.parentNode.children].indexOf(el) : -1;childSelector, и они не должны учитываться, то третий вариант не подходит, а во втором надо заменить index++ на index += el.matches(childSelector).
document.addEventListener('keypress', function(e) {
if (e.keyCode === 32) {
console.log('space pressed');
}
});
document.addEventListener('wheel', function(e) {
const event = new Event('keypress');
event.keyCode = 32;
document.dispatchEvent(event);
});
работает, но не всегда корректно <...> точно есть ошибки
SELECT t1.time, t1.value AS temp_val, t2.value AS hum_val
FROM topics t1
JOIN topics t2 ON t2.time = t1.time
WHERE
t1.topic = 'tempinroom' AND
t2.topic = 'huminroom'
при вводе каждого символа с поля слетает фокус
this.form.company_ids.push({
key: this.form.company_ids.length,
});this.form.company_ids.push({
key: ++this.currKey,
});this.form.company_ids.push({
key: Math.max(0, ...this.form.company_ids.map(n => n.key)) + 1,
});
const selector = 'div p';
const removeFirst = 5;
const removeLast = 3;document.querySelectorAll(selector).forEach((n, i, a) => {
if (i < removeFirst || i > a.length - removeLast - 1) {
n.remove();
}
});document.querySelectorAll([
`${selector}:nth-child(-n+${removeFirst})`,
`${selector}:nth-last-child(-n+${removeLast})`,
]).forEach(n => n.replaceWith());
<div class="counter">
<button class="minus">-</button>
<input type="number" min="2" max="17" value="5">
<button class="plus">+</button>
</div>const updateInput = change => e =>
$('input', e.delegateTarget).val(function(i, v) {
const min = this.min || -Infinity;
const max = this.max || Infinity;
return Math.max(min, Math.min(max, (v | 0) + change));
});
$('.counter')
.on('click', '.minus', updateInput(-1))
.on('click', '.plus', updateInput(1))
.on('input', updateInput(0));const updateInput = change => e => {
const input = e.target.closest('.counter').querySelector('input');
const min = input.min || -Infinity;
const max = input.max || Infinity;
input.value = Math.min(max, Math.max(min, (input.value | 0) + change));
};
document.querySelectorAll('.counter').forEach(function(n) {
n.querySelector('.minus').addEventListener('click', this[0]);
n.querySelector('input').addEventListener('input', this[1]);
n.querySelector('.plus').addEventListener('click', this[2]);
}, [ -1, 0, 1 ].map(updateInput));document.addEventListener('click', ({ target: t }) => {
const change = -t.matches('.plus') || +t.matches('.minus');
if (change) {
const input = t.closest('.counter').querySelector('input');
input.value -= change;
input.dispatchEvent(new Event('input', { bubbles: true }));
}
});
document.addEventListener('input', ({ target: t }) => {
if (t.closest('.counter')) {
t.value = Math.min(t.max || Infinity, Math.max(t.min || -Infinity, t.value | 0));
}
});<button class="minus" data-change="-1">-</button>
<button class="plus" data-change="+1">+</button>document.addEventListener('input', updateInput);
document.addEventListener('click', updateInput);
function updateInput({ target: t }) {
const counter = t.closest('.counter');
if (counter) {
const input = counter.querySelector('input');
const min = input.min || -Infinity;
const max = input.max || Infinity;
input.value = Math.min(max, Math.max(min, (input.value | 0) + (t.dataset.change | 0)));
}
}