- indexToHeaderList = String(headerArr[choosenElem]);
+ indexToHeaderList = headerArr[choosenElem].innerText;
оператором typeof - пишет что это строкаНу так вы же по-любому на typeof проверяли после того как сами руками к строке привели?
let runWithRetry = async (func, tries = 5) => {
let attempt = 1;
while (attempt <= tries) {
try {
return await func();
} catch (error) {
console.log(`Attempt #${attempt} failed: ${error}`);
attempt++;
}
}
throw new Error(`Failed after ${tries} tries`);
};
try {
let busyWork = () => new Promise((resolve, reject) => {
setTimeout(() => (Math.random() > 0.75 ? resolve(Math.random()) : reject()), 1000);
});
let result = await runWithRetry(busyWork, 5);
console.log(result);
} catch (error) {
console.error(error);
}
.nav ul li a.active {
text-decoration: underline;
text-decoration-thickness: 2px;
text-underline-offset: .1em;
}
const $links = document.querySelectorAll('.nav a');
Array.from($links).forEach(($link) => {
$link.addEventListener('click', (event) => {
document.querySelector('.nav a.active')?.classList.remove('active');
event.target.classList.add('active');
})
});
history.pushState({}, '', '/www?' + $(this).serialize());
https://developer.mozilla.org/en-US/docs/Web/API/H... let arr = [1, true, 1, 'null', 1, '2', '1', true, 1, true, 'null', true, 'null'];
let res = arr.filter((el) => arr.filter((i) => i === el).length <= 3);
console.log(res); // ['null', '2', '1', 'null', 'null']
function solution(input, threshold = 3) {
let counter = new Map();
input.forEach((item) => {
let prevCount = counter.get(item) || 0;
counter.set(item, prevCount + 1);
})
let valid = [];
counter.entries().forEach(([item, count]) => {
if (count <= threshold) {
valid.push(item);
}
});
return input.filter((item) => valid.includes(item));
}
let arr = [1, true, 1, 'null', 1, '2', '1', true, 1, true, 'null', true, 'null'];
console.log(solution(arr)); // ['null', '2', '1', 'null', 'null']
function solution(input, threshold = 3) {
let result = [];
let counter = new Map();
input.forEach((item) => {
let prevCount = counter.get(item) || 0;
let count = prevCount + 1;
counter.set(item, count);
if (count <= threshold) {
result.push(item);
}
})
return result;
}
let arr = [1, true, 1, 'null', 1, '2', '1', true, 1, true, 'null', true, 'null'];
console.log(solution(arr)); // [1, true, 1, 'null', 1, '2', '1', true, true, 'null', 'null']
document.getElementById('9')
возвращает null, нет на странице такого элемента. Почему его нет, по приведённому коду сказать невозможно.document.referrer
по F5 не меняется. console.log({...names});
console.log(JSON.parse(JSON.stringify(data)));
beforeunload
злоупотребляют спамеры, поэтому полагаться на него не стоит (не говоря о том, что это костыль). element.style.backgroundColor = value
.Здесь можно даже и не заподозрить, что then что-то возвращает.Все функции в js что-то возвращают. Если явного return нет или в нём не указано значение, то возвращается undefined.
Но поскольку там null, можно подумать, что исходный промис просто как-то передается дальше.Так и есть - вы не передали никакой callback и весь этот вызов как бы игнорируется. Этот сценарий аналогичен предыдущему.
Еще интереснее - then возвращает простое значение, которое моментально попадает в следующий then.Это ваш callback возвращает простое значение, которое then оборачивает в отрезолвленный промис.
Можете рассказать в общих чертах, если then возвращает промис, то как он его формирует?Ну берёт и формирует... Примерно так:
then = (onFulfilledCallback, onRejectedCallback) => {
try {
let newValue;
if (this.previousValue instanceof Error) {
newValue = onRejectedCallback(this.previousValue);
} else {
newValue = onFulfilledCallback(this.previousValue);
}
if (newValue instanceof Promise) {
return newValue;
} else {
return Promise.resolve(newValue);
}
} catch (error) {
return Promise.reject(error);
}
}
Это псеводокод но общий смысл такой. let makeItDouble = (text) => {
let i = text + text;
return i;
};
console.log(makeItDouble("I never look back"));
Return всё прекрасно возвращает. Но то, что он возвращает, нужно сохранять в переменную или использовать сразу. Переменная i находится внутри функции и снаружи недоступна. Если бы можно было делать так, как вы написали, то и смысла в return бы не было. Parameters
indexStart
The index of the first character to include in the returned substring.
indexEnd
Optional
The index of the first character to exclude from the returned substring.
Description
IfindexStart < 0
, the index is counted from the end of the string. More formally, in this case, the substring starts atmax(indexStart + str.length, 0)
.
IfindexEnd < 0
, the index is counted from the end of the string. More formally, in this case, the substring ends atmax(indexEnd + str.length, 0)
.
зачем нужен (-2, -1)Для выполнения вот этого условия задачи: "если слово заканчивается на мягкий знак, то получите предпоследнюю букву". Я искренне не понимаю, что тут можно добавить...
sliceHandler
передаёте div-обёртку, а внутри функции думаете, что это какой-то его ребёнок.key
через атрибут html-тега. Значение key
даже через props
нельзя получить, не говоря уже про html.setInterval(function () {
const $element = document.querySelector("#content > div > div.taskblackout");
if ($element && $element.style.display === 'block') {
document.location.reload()
}
}, 5000);
const check = () => {
const $element = document.querySelector("#content > div > div.taskblackout");
if ($element && $element.style.display === 'block') {
document.location.reload()
} else {
setTimeout(check, 5000);
}
};
setTimeout(check, 5000);