.hidden { display: none; }
document.querySelectorAll('li')
.forEach(li => li.classList.toggle('hidden', !li.querySelector('span')));
для каждого элемента списка устанавливает или снимает класс hidden
, в зависимости от того, найдётся ли span
где-нибудь внутри этого элемента. const tensor = tf.squeeze(result);
const canvas = document.createElement('canvas');
canvas.width = tensor.shape.width
canvas.height = tensor.shape.height
await tf.browser.toPixels(tensor, canvas);
const cat2 = document.createElement('img');
cat2.src = canvas.toDataURL();
Math.sqrt(N)
// дизель* генератор
const ltSqr = function*(n) {
const limit = Math.min(100, Math.sqrt(n));
let i = 1;
while (i <= limit) {
yield i++;
}
}
// использование
let N = 42;
for (const x of ltSqr(N)) {
console.log(x);
}
// выведет натуральные от 1 до 6
https://cdn.jsdelivr.net/npm/sweetalert2@11.4.8
DISCLAIMER
Реализации сортировки могут быть разными.{ // выполнить в консоли браузера
const oneTest = () => {
let iterations = 0;
[1, 2, 3].sort((a, b) => {
const result = Math.random() > Math.random() ? 1 : -1;
console.log(`${iterations}: ${a} vs ${b} = ${result}`);
iterations++;
return result;
});
return iterations;
}
console.clear();
const totalTests = 10;
const stats = {};
for (let test = 0; test < totalTests; test++) {
console.group(`Test ${test + 1} of ${totalTests}`);
const iterations = oneTest();
stats[iterations] ??= 0;
stats[iterations]++;
console.groupEnd();
}
console.log(JSON.stringify(stats, null, 2));
}
$options = [
[null, $_LNG['TYPE_ORDER']],
['select_all', $_LNG['ALL_TYPES']],
['select_domain', $_LNG['DOMAIN']],
['select_server', $_LNG['SERVER']],
['select_ssl', $_LNG['SSL']],
['select_desing', $_LNG['DESING']],
['select_script', $_LNG['SCRIPT']],
['select_layout', $_LNG['LAYOUT']],
['select_adv', $_LNG['ADV']],
['select_seo', $_LNG['SEO']],
];
printf('const options = %s;', json_encode($options));
options
полноценный элемент select
со всеми опциями: createSelect = () => {
const select = document.createElement('select');
options.forEach(([value, title]) => {
const option = document.createElement('option');
option.innerText = title;
if (value) {
option.value = value;
} else {
option.setAttribute('disabled', true);
option.setAttribute('selected', true);
}
select.appendChild(option);
});
return select;
};
возвращает массив индексов элементов, у которые значение равно value.
const findIndex = (arr, value) => arr
.map((v, i) => ({ v, i }))
.filter(({ v }) => v === value)
.map(({ i }) => i);
Каждый элемент массива переделать в объект, где v
: элемент, а i
: индекс в массиве.бывш.элемент === value
i
setAttribute("disabled", true)
в зависимости от заполненности всех. Слушателем события "input" на каждом из полей вызывать эту функцию. const library = books.reduce((acc, c) => (acc[c.id] = c, acc), {});
const result = users.map(user => {
const books = user.books.map(id => library[id]);
return { ...user, books };
});
Codepen function addPointCenter(index) {
const avg = (a, b) => (a + b) / 2;
const midPoint = (p1, p2) => ({ lat: avg(p1.lat, p2.lat), lng: avg(p1.lng, p2.lng) });
const insert = (index, point) => latlng.splice(index, 0, point);
const { length } = latlng;
const current = latlng[index];
const indexLeft = (index - 1 + length) % length;
const pointLeft = midPoint(current, latlng[indexLeft]);
const indexRight = (index + 1) % length;
const pointRight = midPoint(current, latlng[indexRight]);
insert(index + 1, pointRight);
insert(index, pointLeft);
drawMarkers();
}
dot.str('qna.habr.com', 'value', this.data);
/* this.data:
{
qna: {
habr: {
com: "value"
}
}
} */
npm install dot-object --save
isLoading
, а свойство некого объекта изменять: flags.isLoading = false;
const PERIOD = 5000;
let timeout;
const action = () => {
console.log('Action!');
// this.switchNextTab()
clearTimeout(timeout);
timeout = setTimeout(action, PERIOD);
};
const flags = {
_isLoading: false,
set isLoading(value) {
this._isLoading = value;
if (!value) {
// isLoading стал false
action();
}
},
get isLoading() {
return this._isLoading;
},
};
timeout = setTimeout(action, PERIOD);
// где-то в коде:
flags.isLoading = true;
// ...
flags.isLoading = false; // тут же выполнится action
001
010
100
Из каждой цифры (0 или 1) делается ячейка таблицы. Строки оборачиваются в тег tr
, и всё это обёртывается в table. Полученный HTML вставляется в страницу.