const elements = document.querySelectorAll('p');
const max = 20;
const text = 'hello, world!!';
let len = 0;
for (const n of elements) {
len += n.innerText.length;
if (len >= max) {
n.parentNode.insertBefore(new Text(text), n.nextSibling);
// или
n.outerHTML += text;
break;
}
}
const el = Array.prototype.find.call(elements, function(n) {
return (this[0] += n.textContent.length) >= max;
}, [ 0 ]);
el?.after(text);
// или
el && el.insertAdjacentText('afterend', text);
function tableString(arr, numCols, colSpacing = 3) {
const numRows = Math.ceil(arr.length / numCols);
const rows = Array.from(
{ length: numRows },
(n, i) => arr.slice(i * numCols, (i + 1) * numCols)
);
const widths = Array.from(
{ length: numCols },
(n, i) => Math.max(...rows.map(m => (m[i] ?? '').length))
);
return rows
.map(n => n.map((m, i) => m.padEnd(colSpacing + widths[i], ' ')).join(''))
.join('\n');
}
const arr = [
'11111', '22222222', '33333333', '444', '11', '222', '3333',
'4444444', '11111111', '222222', '33333333', '4', '1',
'2222222222', '3', '44444444444444',
];
console.log(tableString(arr, 4));
console.log(tableString(arr, 3));
console.log(tableString(arr, 3, 8));
totalTon() {
return this.number * this.options.find(n => n.value === this.selected).ton;
},
:value="option.value"
сделайте :value="option"
.total() {
return this.number * this.selected.value;
},
totalTon() {
return this.number * this.selected.ton;
},
/*
* надеюсь, хотя бы вместо "по всему документу" вы сумеете подобрать
* какой-нибудь вменяемый селектор, чтобы не проверять реально всё,
* а только те элементы, где ваш "undefined" действительно может случиться
*/
document.querySelectorAll('*').forEach(n => {
const text = n.innerText?.trim();
if (text === 'undefined') {
n.hidden = true;
}
});
v-model="sum[product.id]"
на :value="sum[product.id]" readonly
.sum() {
return Object.fromEntries(Object.entries(this.price).map(n => ([
n[0],
(this.result[n[0]] || 0) * n[1],
])));
},
const arr = str.split(/(?<=[A-Z]), /);
// или
const arr = str.match(/[^,\s][^,]*, [^,]+/g) ?? [];
// или
const arr = str
.split(', ')
.reduce((acc, n, i) => (
(i & 1) || acc.push([]),
acc[acc.length - 1].push(n),
acc
), [])
.map(n => n.join(', '));
.hidden {
display: none;
}
const filter = document.querySelector('.filter');
filter.addEventListener('change', function() {
document.querySelectorAll('.cart-product').forEach(function(n) {
n.classList.toggle('hidden', this.length && !this.includes(n.dataset.category));
}, Array.from(this.querySelectorAll(':checked'), n => n.dataset.filter));
});
filter.dispatchEvent(new Event('change'));
@click="e => e.stopImmediatePropagation()"
в дочернем компоненте.stop
, нужен объект события. Его можно прокидывать из компонента, на экземпляре которого ловите клик, т.е., там на корневом элементе должно быть @click="$emit('click', $event)"
. Или, добавляем модификатор native
: @click.native.stop
. function showDotsCountInPolygon(e) {
const dotsCountInPolygon = dots
.filter(n => google.maps.geometry.poly.containsLocation(new google.maps.LatLng(n), this))
.length;
infoWindow.setContent(`Точек в полигоне: ${dotsCountInPolygon}`);
infoWindow.setPosition(e.latLng);
infoWindow.open(map);
}
polygon.addListener('click', showDotsCountInPolygon);
function createTreeData(arr, idKey, parentKey) {
const tree = Object.fromEntries(arr.map(n => [ n[idKey], { ...n, children: [] } ]));
return Object.values(tree).filter(n => !tree[n[parentKey]]?.children.push(n));
}
const treeData = createTreeData(data, 'id', 'parent_id');
const createTreeHTML = data =>
Array.isArray(data) && data.length
? `<ul>${data.map(n => `
<li>
${n.name}
${createTreeHTML(n.children)}
</li>`).join('')}
</ul>`
: '';
document.body.insertAdjacentHTML('beforeend', createTreeHTML(treeData));
const createTreeElement = data =>
data instanceof Array && data.length
? data.reduce((ul, n) => (
ul.append(document.createElement('li')),
ul.lastChild.append(n.name, createTreeElement(n.children)),
ul
), document.createElement('ul'))
: '';
document.body.append(createTreeElement(treeData));
function createTreeElement(arr, idKey, parentKey) {
const tree = arr.reduce((acc, { [parentKey]: n }) => (
acc[n] = acc[n] ?? document.createElement('ul'),
acc
), {});
arr.forEach(n => (
tree[n[parentKey]].append(document.createElement('li')),
tree[n[parentKey]].lastChild.append(n.name, tree[n[idKey]] ?? '')
));
return Object.values(tree).reduce((ul, n) => (
n.parentNode || ul.append(...n.children),
ul
), document.createElement('ul'));
// или, если не надо объединять в общий список элементы, у которых разные корневые parent_id
// return Object.values(tree).filter(n => !n.parentNode);
}
document.body.append(createTreeElement(data, 'id', 'parent_id'));
пользовательский хук не обязательно должен иметь конкретную сигнатуру. Мы можем решить, что он принимает в качестве аргументов, и должен ли он что-либо возвращать. Другими словами, всё как в обычных функциях.
const newArr = [...Array(num)].reduce((acc, n, i) => (
acc[(index + i) % acc.length]++,
acc
), [...arr]);
// или
const newArr = arr.map(function(n, i, a) {
return n + this[0] + (((i - index) % a.length + a.length) % a.length < this[1]);
}, [ num / arr.length | 0, num % arr.length ]);
for (let i = num; i-- > 0; arr[(index + i) % arr.length]++) ;
// или
(function xxx(i) {
if (--i >= 0) {
arr[(index + i) % arr.length]++;
xxx(i);
}
})(num);
В чем моя ошибка?
const sum = val =>
val instanceof Object
? Object.values(val).reduce((acc, n) => acc + sum(n), 0)
: typeof val === 'number'
? val
: 0;
console.log(sum(obj));
function sum(val) {
let result = 0;
for (const stack = [ val ]; stack.length;) {
const n = stack.pop();
if (n instanceof Object) {
stack.push(...Object.values(n));
} else if (n === +n) {
result += n;
}
}
return result;
}