const options = [
[ 'hello, world!!', 'fuck the world', 'fuck everything' ],
500,
(elem => item => elem.textContent = item)
(document.querySelector('.slide-words')),
];function interval(arr, delay, callback) {
let i = -1;
return arr.length
? setInterval(() => callback(arr[i = -~i % arr.length]), delay)
: null;
}
const intervalId = interval(...options);
// надо остановить, делаем так: clearInterval(intervalId);function interval(arr, delay, callback) {
let timeoutId = null;
arr.length && (function next(i) {
timeoutId = setTimeout(() => {
callback(arr[i]);
next((i + 1) % arr.length);
}, delay);
})(0);
return () => clearTimeout(timeoutId);
}
const stop = interval.apply(null, options);
// надо остановить, делаем так: stop();
parseInt('') будет NaN.0 вместо мусорных результатов парсинга, замените parseInt($(this).val()) на parseInt($(this).val()) || 0.
<span>hello, world!!... fuck the world... fuck everything</span>body {
margin: 0;
background: black;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
span {
color: red;
font-size: 24px;
font-family: monospace;
}
.xxx {
display: inline-block;
min-width: 10px;
transition: all 0.2s;
transform: scale(1);
}
.hidden {
opacity: 0;
transform: scale(30);
}function show(el) {
el.innerHTML = Array
.from(el.innerText, n => `<span class="xxx hidden">${n}</span>`)
.join('');
el.querySelectorAll('span').forEach((n, i) => {
setTimeout(() => n.classList.remove('hidden'), 100 * i);
});
}
show(document.querySelector('span'));
const getText = el => el.textContent;
// или
const getText = el => el.innerText;
// или
const getText = el => el.innerHTML;
// или
const getText = el => el.lastChild.nodeValue;
// или
const getText = el => el.childNodes[0].data;const getValue = text => text.match(/"(.*?)"/)[1];
// или
const getValue = text => text.split('"').slice(-2).shift();
// или
const getValue = text => text.replace(/^.*?"|"[^"]*$/g, '');
//
const getValue = text => `${/(?<=")[^"]+/.exec(text)}`;
// или
const getValue = text =>
JSON.parse(text.slice(-~text.indexOf('['), text.indexOf(']')));document.querySelectorAll('li button').forEach(function(n) {
n.addEventListener('click', this);
}, e => console.log(getValue(getText(e.target))));
// или
document.querySelector('ul').addEventListener('click', ({ target: t }) => {
if (t.tagName === 'BUTTON') {
console.log(getValue(getText(t)));
}
});
const sums = arr.reduce((acc, n, i) => (
(i & 1) || acc.push(0),
acc[acc.length - 1] += n,
acc
), []);
// или
const sums = arr.reduce(
(acc, n, i) => (acc[i / 2 | 0] += n, acc),
Array(Math.ceil(arr.length / 2)).fill(0)
);
// или
const sums = Array.from(
{ length: arr.length / 2 + arr.length % 2 },
(n, i) => arr[i * 2] + (arr[i * 2 + 1] || 0)
);
// или
const sums = eval(`[${arr}]`.replace(/(\d+),(\d+)/g, '$1+$2'));const result = sums.join(' ');
// или
const result = sums.reduce((acc, n) => acc + (acc && ' ') + n, '');
// или
const result = ''.concat(...sums.flatMap((n, i) => i ? [ ' ', n ] : n));
// или
const result = String(sums).replace(/,/g, ' ');
const card = document.querySelector('.card');
const itemsExists = () => !!card.querySelector('.item');const nav = document.querySelector('.navigation');
// или, если слова про соседа являются правдой
const nav = card.nextElementSibling;nav.hidden = !itemsExists();
// или
nav.style.display = itemsExists() ? 'block' : 'none';.card:not(:has(.item)) + .navigation {
display: none;
}
const isPositiveInteger = RegExp.prototype.test.bind(/^\d+$/);
// или
const isPositiveInteger = str =>
!(!str || str.replace(/\d/g, ''));
// или
const isPositiveInteger = str =>
Boolean(str) && !str.match(/\D/);Нужна именно регулярка, т.к. числа большой длины.
const isPositiveInteger = str =>
str !== '' && [...str].every(n => Number.isInteger(+n));
// или
function isPositiveInteger(str) {
for (const n of str) {
if (!'0123456789'.includes(n)) {
return false;
}
}
return str.length > 0;
}
// или
function isPositiveInteger(str) {
let result = !!str;
for (let i = 0; i < str.length && result; i++) {
const n = str.charCodeAt(i);
result = 47 < n && n < 58;
}
return result;
}
const containerSelector = '.form-fields';
const itemSelector = `${containerSelector} .wrapper-from-field`;
const activeClass = 'active';
const toggle = item => item
.closest(containerSelector)
.querySelectorAll(itemSelector)
.forEach(n => n.classList.toggle(activeClass, n === item));document.querySelectorAll(itemSelector).forEach(function(n) {
n.addEventListener('change', this);
}, e => toggle(e.currentTarget));
// или
document.addEventListener('change', ({ target: t }) =>
(t = t.closest(itemSelector)) && toggle(t)
);
const getCard = button => $(`#card${button.id.match(/\d+/).pop()}`);
$('[id^="button"]').hover(
e => getCard(e.target).fadeIn(),
e => getCard(e.target).fadeOut(),
);const $buttons = $('[id^=button]').hover(function(e) {
this.eq($buttons.index(e.target))[e.type === 'mouseenter' ? 'fadeIn' : 'fadeOut']();
}.bind($('[id^=card]')));
// смотрим, что скажет оператор typeof
const isString = x => typeof x === 'string';
// сравниваем значение и результат его преобразования в строку
const isString = x => x === `${x}`;
// проверяем конструктор (помимо примитивов, выдаёт true и для строковых объектов)
const isString = x => x != null && x.constructor === String;// cобираем новый массив
const newArr = arr.filter(n => !isString(n));
// удаляем элементы существующего
arr.length -= arr.reduce((acc, n, i, a) => (
a[i - acc] = n,
acc + isString(n)
), 0);
top += 2, вы вовсе не с числом работаете. Меняйте имя переменной или выполняйте свой код в области видимости, отличной от глобальной или сделайте свой top свойством какого-нибудь объекта или...
select.innerHTML = [
{ val: 69, optionText: 'hello, world!!', selectText: 'HELLO, WORLD!!' },
{ val: 187, optionText: 'fuck the world', selectText: 'FUCK THE WORLD' },
{ val: 666, optionText: 'fuck everything', selectText: 'FUCK EVERYTHING' },
].map(n => `
<option value="${n.val}" hidden>${n.selectText}</option>
<option value="${n.val}">${n.optionText}</option>
`).join('');
select.addEventListener('change', e => e.target.value = e.target.value);
const source = document.querySelector('.menu');
const target = document.querySelector('#parent');for (const n of source.children) {
target.appendChild(n.cloneNode(true));
}
// или
source.querySelectorAll(':scope > *').forEach(n => {
target.insertAdjacentElement('beforeend', n.cloneNode(true));
});// вложенные узлы копии добавляем в целевой элемент
target.append(...source.cloneNode(true).children);
// или, заменяем целевой элемент копией исходного
target.replaceWith(source.cloneNode(true));target.innerHTML = source.innerHTML;
// или
target.outerHTML = source.outerHTML;