let isInIframe;
try {
isInIframe = window.self !== window.top;
} catch (e) {
isInIframe = true;
}
if (isInIframe) {
// мы в айфрейме
}
Дальше можно запрашивать, например, основной контент страницы, добавив параметры к запросу https://example.com/page.php?iframe=1
const sum = number => {
if (number < 0) return 0;
// вспомогательная функция считает сумму ряда с шагом step
const sequenceSum = step => {
const q = Math.floor(number / step);
return q * (q + 1) * step / 2;
}
return sequenceSum(3) + sequenceSum(5) - sequenceSum(3 * 5);
}
// использование
sum(999999) // мгновенно: 233333166668
const sum = number => {
if (number < 0) return 0;
// вспомогательная функция считает сумму ряда с шагом step
const sequenceSum = step => {
const q = Math.floor(number / step);
return q * (q + 1) * step / 2;
}
return sequenceSum(3) + sequenceSum(5) - sequenceSum(3 * 5);
}
sum(18) // 78
h = g * t^2 / 2
, где g — постоянная, ускорение свободного падения. В игре не метры, а пиксели, и надо подобрать значение константы, чтобы не слишком быстро, не слишком медленно ускорялось тело. На глаз.update()
. Это достаточно сделать только 1 раз.let startTime = Date.now();
// Функция Прыжка
const moveUp = () => {
ghost.y -= 50;
startTime = Date.now();
};
document.addEventListener('keydown', moveUp);
function update() {
// Физика
const dt = Date.now() - startTime;
ghost.y += dt ** 2 / 100; // подобрать число
// Границы
ghost.x = Math.min(900, Math.max(0, ghost.x));
ghost.y = Math.min(650, Math.max(0, ghost.y));
}
new Array(15).fill('').map((_, i) => i / 3 & 1 ? '+' : '-').join(',')
"-,-,-,+,+,+,-,-,-,+,+,+,-,-,-"
new Array(15).fill().map((_, i) => i)
.reduce((acc, c, i) => {
if (i % 3 === 0) acc.push([]);
acc[acc.length - 1].push(c);
return acc;
}, []);
// "[[0,1,2],[3,4,5],[6,7,8],[9,10,11],[12,13,14]]"
e.target
— увидите, что за элемент поймал клик.<div class="burger">
<span>Какой-то текст</span>
</div>
тут часть кликов поймает не div
, а span
. Но, если добавить span'у CSS-свойство pointer-events: none;
, он перестанет взаимодействовать с мышкой, и все клики отловятся именно div'ом, как и задумывалось. toCurrency(100500, 'BYN', 'be-BY')
у меня возвращает строку "100 500,00 Br"
toCurrency(100500, 'BYN', 'ru-BY');
const re = new RegExp('(\\d{2}).(\\d{2}).(\\d{4})');
const tests = ['05.05.2020', '05/05/2020', '05/05/2020;22:40', '5', '5.1', '5.23'];
tests.forEach(str => console.log(`${str}: ${re.test(str)}`));
/*
05.05.2020: true
05/05/2020: true
05/05/2020;22:40: true
5: false
5.1: false
5.23: false
*/
ваши «тесты» проходит ) let bgIndex = 0;
appBackground.backgroundParrent.addEventListener('click', () => {
const url = backgroundArrayImg[(++bgIndex) % backgroundArrayImg.length];
document.querySelector('body').style.backgroundImage = `url(${url})`;
});
true
.price
.undefined
, если не найден.const data = [
{"nmId":22457195,"price":1947,"discount":30,"promoCode":0},{"nmId":22457420,"price":1400,"discount":27,"promoCode":0},
{"nmId":22458138,"price":1486,"discount":16,"promoCode":0},{"nmId":41678969,"price":1431,"discount":0,"promoCode":0}
];
const getPriceByNmId = nmId => data.find(item => item.nmId === nmId)?.price;
getPriceByNmId(22457195) // 1947
getPriceByNmId(100500) // undefined
const results = Object.values(arr.reduce((acc, c) => {
const prefix = c.id.split('.')[0];
acc[prefix] = [...acc[prefix] ?? [], c];
return acc;
}, {})
);
/* [
[{"id":"0"},{"id":"0.0"},{"id":"0.1"},{"id":"0.2"},{"id":"0.3"}],
[{"id":"1"},{"id":"1.0"},{"id":"1.1"}],
[{"id":"2"},{"id":"2.0"},{"id":"2.1"},{"id":"2.2"}],
] */
const getLeaders = numbers =>
numbers.reduceRight(
(acc, c) => { // acc – аккумулятор, c – очередной элемент массива
if (c > acc.sum) { // если больше суммы тех, что правее
acc.result.unshift(c); // положить в массив результатов
}
acc.sum += c; // накапливать сумму
return acc; // аккумулятор пойдёт в следующую итерацию
},
{ result: [], sum: 0 } // начальное значение acc
)
.result; // в итоге интересует только массив result
// использование
getLeaders([16, 17, 5, 4, 3, 1]) // [ 17, 3, 1 ]
const arrA = a[0].trim().split("\n");
// [ "123", "1234", "12345", "123456" ]
const arrB = b[0].trim().split("\n");
// [ "a", "b", "c", "d" ]
const arrAB = arrA.map((str, index) => `${arrB[index]}: ${str}`);
// [ "a: 123", "b: 1234", "c: 12345", "d: 123456" ]
arrAB.join("\n")
/*
"a: 123
b: 1234
c: 12345
d: 123456"
*/
const a = ['123', '1234', '12345', '123456'];
const b = ['a', 'b', 'c', 'd'];
const replace = (search, a, b) => {
const result = a.slice(); // копия
const index = a.indexOf(search);
if (index > -1) result.splice(index, 1, b[index]);
return result;
}
replace('1234', a, b)
// [ "123", "b", "12345", "123456" ]