const result = arr.reduce((acc, n) => acc * n.values, 1);const result = eval(arr.map(n => n.values).join('*')) ?? 1;let result = 1;
for (const { values: n } of arr) {
result *= n;
}let result = 1;
for (let i = 0; i < arr.length; i++) {
result = result * arr[i].values;
}const result = (function mul(i) {
return i >= arr.length
? 1
: arr[i].values * mul(-~i);
})(0);
const url = new URL('https://qna.habr.com/?test=123&frukt=yabloko');
console.log(url.searchParams.get('test'));const str = 'https://qna.habr.com/?test=123&frukt=yabloko';
const usp = new URLSearchParams(str.replace(/^[^?]*\?/, '')); // или str.split('?').pop()
console.log(usp.get('test'));
Обратите внимание: когда изменяете (а не заменяете) объект или массив, старое и новое значения при вызове коллбэка будут совпадать, так как они ссылаются на один и тот же объект или массив. Vue не сохраняет копии объекта на момент, предшествовавший изменениям.
watch: {
'obj.propName'(newValue, oldValue) {
...
},
},obj.propName = value, а будет obj = { ...obj, propName: value }. Ну а дальше можно уже сравнивать свойства в старом и новом объектах, чтобы найти, какое конкретно было изменено.
{ имя валюты, относительная стоимость }.
[ 5, 8, 10 ].forEach((n, i, a) => $items.slice(a[i - 1], n).wrapAll('<div>'));
const elements = document.querySelectorAll('.wrapper-boxes');
const tag = 'button';
const text = 'click me';
const className = 'xxx';elements.forEach(n => {
n.after(document.createElement(tag));
n.nextSibling.textContent = text;
n.nextSibling.classList.add(className);
});for (const { parentNode, nextSibling } of elements) {
const el = document.createElement(tag);
el.innerText = text;
el.className = className;
parentNode.insertBefore(el, nextSibling);
}for (let i = 0; i < elements.length; i++) {
elements[i].insertAdjacentHTML(
'afterend',
`<${tag} class="${className}">${text}</${tag}>`
);
}(function insert(i, n = elements.item(i)) {
if (n) {
const el = document.createElement(tag);
el.appendChild(new Text(text));
el.classList.value = className;
n.insertAdjacentElement('afterend', el);
insert(-~i);
}
})(0);
const arr = Object
.entries(obj)
.reduce((acc, [ k, values ]) => (
values.forEach((v, i) => (acc[i] ??= {})[k] = v),
acc
), []);const keys = Object.keys(obj);
const arr = obj[keys[0]]?.map((_, i) => {
return Object.fromEntries(keys.map(k => [ k, obj[k][i] ]));
}) ?? [];const zip = (arrs, defaultValue = null) =>
Array.from(
{ length: Math.max(...arrs.map(n => n.length)) },
(_, i) => arrs.map(n => i < n.length ? n[i] : defaultValue)
);
const combine = (keys, values, defaultValue = null) =>
keys.reduce((acc, n, i) => (
acc[n] = i < values.length ? values[i] : defaultValue,
acc
), {});
const arr = Array.from(
zip(Object.values(obj)),
combine.bind(null, Object.keys(obj))
);
const index = 0;.const duplicates = arr.filter((n, i, a) => a.filter(m => m[index] === n[index]).length > 1);const duplicates = Object
.values(arr.reduce((acc, n) => ((acc[n[index]] ??= []).push(n), acc), {}))
.flatMap(n => ~-n.length ? n : []);const duplicates = Array
.from(arr.reduce(
(acc, n) => (acc.get(n[index]).push(n), acc),
new Map(arr.map(n => [ n[index], [] ]))
).values())
.reduce((acc, n) => (n.length > 1 && acc.push(...n), acc), []);const duplicates = arr.filter(function(n) {
return this.get(n[index]);
}, arr.reduce((acc, { [index]: n }) => acc.set(n, acc.has(n)), new Map));
document.querySelector('.btn--start').addEventListener('click', filterItems);
document.querySelector('select').addEventListener('change', e => e.target.value === 'all' && filterItems());
function filterItems() {
const val = document.querySelector('select').value;
document.querySelectorAll('.item').forEach(n => {
n.style.display = [ n.dataset.elem, 'all' ].includes(val)
? 'block'
: 'none';
});
}
Object.fromEntries(new URLSearchParams(arr.join('&')))arr.reduce((acc, n) => (
n = n.split('='),
acc[n[0]] = n[1],
acc
), {})Object.assign(...arr.map(n => n.match(/[^=]+/g)).map(([ k, v ]) => ({ [k]: v })))eval(`({${arr.map(n => `"${n.replace('=', '":"')}"`)}})`)
<div data-value="69"></div>
<div data-value="187"></div>
<div data-value="666"></div>function animateValue(elem) {
return new Promise(resolve => {
const endValue = +elem.dataset.value;
let currValue = 0;
const interval = setInterval(() => {
if (++currValue === endValue) {
clearInterval(interval);
resolve();
}
elem.innerText = currValue;
}, 20);
});
}
Array
.from(document.querySelectorAll('[data-value]'))
.reduce((p, c) => p.then(() => animateValue(c)), Promise.resolve());
The useRef() Hook isn’t just for DOM refs. The “ref” object is a generic container whose current property is mutable and can hold any value, similar to an instance property on a class.
justify-content распределяет содержимое блока вдоль главной оси, в качестве которой у вас установлена вертикальная (flex-direction: column).align-items.
const result = arr.reduce((acc, n, i) => (
(i & 1) || acc.push(0),
acc[~-acc.length] += n,
acc
), []);function* chunked(data, chunkSize) {
const iter = data[Symbol.iterator]();
for (let chunk = [], n; !n?.done && (n = iter.next());) {
if (!n.done) {
chunk.push(n.value);
}
if (chunk.length === chunkSize || (n.done && chunk.length)) {
yield chunk;
chunk = [];
}
}
}
function sum(data, val = n => n) {
const getVal = val instanceof Function ? val : n => n[val];
let result = 0;
for (const n of data) {
result += getVal(n);
}
return result;
}const result = Array.from(chunked(arr, 2), n => sum(n));
isOpen с помощью директивы v-model, замените :is-open="item.isOpen" на v-model:is-open="item.isOpen".isOpen = !isOpen на $emit('update:isOpen', !isOpen).
.active {
&::after {
content: "hello, world!!";
}
}<a class="tabs-select__button" data-text="hello, world!!">
<a class="tabs-select__button" data-text="fuck the world">.active {
&::after {
content: attr(data-text);
}
}
const flatArr = arr.flatMap(n => Array.isArray(n.DOP) ? n.DOP : []);
// или
const flatArr = Array.prototype.concat.apply([], arr.map(n => n.DOP ?? []));
// или
const flatArr = arr.reduce((acc, n) => (n.DOP && acc.push(...n.DOP), acc), []);const unique = Object.values(Object.fromEntries(flatArr.map(n => [ n.NAME, n ])));
// или
const unique = flatArr.filter(function({ NAME: n }) {
return !(this[n] = this.hasOwnProperty(n));
}, {});
// или
const unique = flatArr.filter((n, i, a) => n === a.find(m => m.NAME === n.NAME));