$(document).click('.e-1', function(event) { console.log(event.target) });
$(document).on('click', '.e-1', function(e) {
console.log(e.currentTarget);
});
'*'
в качестве результата, реально вы выдаёте '*\n'
..join('\n')
. Ну и ещё пробелов не хватает после звёздочек.const christmasTree = length =>
Array.from({ length }, (n, i) => (
n = ' '.repeat(length - i - 1),
n + '*'.repeat(i * 2 + 1) + n
)).join('\n');
const random = arr => arr[Math.random() * arr.length | 0];
const item = random(random(Object.values(state.themes)));
const item = random(Object.values(state.themes).flat());
function weightedRandom(arr, key) {
const rand = Math.random() * arr.reduce((acc, n) => acc + n[key], 0);
let sum = 0;
return arr.find(n => (sum += n[key]) > rand);
}
const item = random(weightedRandom(Object.values(state.themes), 'length'));
const elements = Array.prototype.filter.call(
document.querySelectorAll('.green'),
(n, i, a) => n.nextElementSibling !== a[i + 1]
);
'.green + .green'
, или при фильтрации дополнительно проверяйте, что n.previousElementSibling === a[i - 1]
. str.split('/').pop()
// или
str.match(/[^\/]+$/)[0]
// или
str.replace(/.*\//, '')
// или
str.slice(str.lastIndexOf('/') + 1)
// или
Array.from(str).reduce((acc, n) => n === '/' ? '' : acc + n, '')
// или
[...str].filter((n, i, a) => !a.includes('/', i)).join('')
const getTruthyKeys = obj =>
Object
.entries(obj)
.filter(n => n[1])
.map(n => n[0]);
for([key, value] of Object.entries(item)) {
const obj = new Proxy({
a: 0,
b: 1,
c: 2,
}, {
get: () => Math.round(Math.random()),
});
console.log(Array.from({ length: 10 }, () => getTruthyKeys(obj)));
const replaceValues = (val, test, replacer) =>
val instanceof Array
? val.map(n => replaceValues(n, test, replacer))
: val instanceof Object
? Object.fromEntries(Object
.entries(val)
.map(([ k, v ]) => [
k,
test(k, v)
? replacer(v)
: replaceValues(v, test, replacer)
])
)
: val;
const newData = replaceValues(
data,
k => k.includes('Date'),
v => v.replace(/(\d+)-(\d+)-/, '$2.$1.')
);
$('.content_toggle').click(function() {
const $button = $(this);
$(`#box-${this.id.split('-').pop()}`).slideToggle(300, function() {
const isHidden = $(this).is(':hidden');
$button
.text(isHidden ? 'Показать текст' : 'Скрыть текст')
.toggleClass('open', !isHidden);
});
return false;
});
$(this).closest('здесь селектор общего предка').find('.content_block')
$(this).next()
$('.content_block').eq($('.content_toggle').index(this))
$(document).on('click', 'a[id^="answer_"]', e => $(`#comment_${e.target.id}`).toggle());
function setNestedVal(root, path, val) {
const keys = path.split('.');
const key = keys.pop();
keys.reduce((acc, n) => acc[n] ??= {}, root)[key] = val;
}
setNestedVal(data, '0.arr.0.str', 'hello, world!!');
setNestedVal(data, '0.arr.1.num', 666);
Интересуют готовые решения
Нужно изменить этот массив, преобразовав все строки с датами в нём, независимо от того, как глубоко они вложены, в объекты.
const replaceValues = (data, test, transform) =>
test(data)
? transform(data)
: data instanceof Array
? data.map(n => replaceValues(n, test, transform))
: data instanceof Object
? Object.fromEntries(Object
.entries(data)
.map(([ k, v ]) => [ k, replaceValues(v, test, transform) ])
)
: data;
const newData = replaceValues(
data,
x => typeof x === 'string' && /^\d{2}\.\d{2}\.\d{4}$/.test(x),
str => new Date(str.split('.').reverse().join('-'))
);
const sum = arr.reduce((acc, n) => acc + n.number, 0);
const newArr = arr.map(n => ({ ...n, percent: n.number / sum * 100 }));
Object
.entries(arr.reduce((acc, n) => (
n = n.match(/('.*?'):'(.*?)'/),
(acc[n[1]] ??= []).push(n[2]),
acc
), {}))
.map(n => `${n[0]}:'${n[1].join('|')}'`)
<script defer src="https://cdnjs.cloudflare.com/ajax/libs/alpinejs/3.3.4/cdn.min.js"></script>
<div x-data="{
items: [
{ id: 69, text: 'hello, world!!' },
{ id: 187, text: 'fuck the world' },
{ id: 666, text: 'fuck everything' },
],
}">
<template x-for="(n, i) in items">
<div>
<span x-text="n.text"></span>
<button @click="items.splice(i, 1)">x</button>
</div>
</template>
</div>
Код, который работает некорректно...
const originalIterator = Array.prototype[Symbol.iterator];
Array.prototype[Symbol.iterator] = function() {
...
};
setTimeout(() => Array.prototype[Symbol.iterator] = originalIterator, 0);
const result = arr.flat();
// или
const result = Array.prototype.concat.apply([], arr);
// или
const result = arr.reduce((acc, n) => (acc.push(...n), acc), []);
// или
const result = [];
for (const n of arr) {
for (const m of n) {
result[result.length] = m;
}
}
document.querySelectorAll('.filter__item').forEach(n => {
n.style.display = Array
.from(n.querySelectorAll('.filter__checkgroup-count'))
.some(m => +m.innerText.trim())
? 'block'
: 'none';
});
.hidden {
display: none;
}
for (const n of document.getElementsByClassName('filter__item')) {
n.classList.toggle('hidden', Array.prototype.every.call(
n.getElementsByClassName('filter__checkgroup-count'),
m => Number(m.textContent.trim()) === 0
));
}