const monthNames = 'января февраля марта апреля мая июня июля августа сентября октября ноября декабря'
.split(' '); // получится массив
const D = new Date(); // объект Даты на сейчас
// завтрашний день
D.setDate( D.getDate() + 1); // так месяц "переключится" автомагически
console.log( 'Завтра ' + D.getDate() + ' ' + monthNames[ D.getMonth() ] );
complete
и после него naturalWidth
(или naturalHeight
) через какое-то время после назначения src
– достаточное для загрузки картинки. Проверка того, есть ли картинка, в любом случае немгновенна, асихнонна.const srcs = [
'https://sun6-5.userapi.com/c850632/v850632804/12d149/KnY01pJH16w.jpg'
,'https://sun6-6.userapi.com/c855020/v855020551/59a81/phM3k4nXcrg.jpg'
];
function makeCheck(image) {
return function() {
if (image.complete && image.naturalWidth) {
console.log("картинка загрузилась ОК!");
} else {
console.error("Нет такой картинки: " + image.src);
}
}
}
for(let i = 0;i < srcs.length; i++) {
const src = srcs[i];
const image = new Image();
window.setTimeout( makeCheck(image), 300);
//image.src = "../img/designers/" + index + '.' + id + ".jpg";
image.src = src;
}
indexOf()
в лоб. Костыль только для двух повторов, но, по идее, быстрее регулярок:function haz2ones(str) {
const s = str.toString();
const search = '1';
let i = s.indexOf(search);
if (!~i) return false;
i = s.indexOf(search, i + 1);
if (!i) return false;
if (!!~s.indexOf(search, i + 1)) return false;
return true;
}
const tests = [
[1, false],
[11, true],
[111, false],
['1', false],
['11', true],
['111', false],
['100001', true],
['000011', true],
[12345678901234567890, true],
];
return tests.map(e => haz2ones(e[0]) === e[1] ? '+' : '- ' + e[0]);
// +,+,+,+,+,+,+,+,+
$('.parent div:last-child').addClass('div2');
Замыкание — это комбинация функции и лексического окружения, в котором эта функция была определена.
A closure is the combination of a function and the lexical environment within which that function was declared.
function makeCounter() {
// далее ваш код:
let count = 0;
function counter() {
return count += 1;
}
// конец вашего кода.
return counter; // вернули Функцию (с её окружением)
}
var myCounter = makeCounter();
// вот теперь к значению count не добраться - приватность!
// зато
console.log(myCounter()); // 1
console.log(myCounter()); // 2
console.log(myCounter()); // 3
const digits = [1,2,3,4,5,6,7,8,9];
const arr = [];
for (let i=0; i<4; i++) {
const n = Math.floor(Math.random() * digits.length);
arr.push( digits.splice(n, 1)[0] );
}
// arr == [2,9,8,1] и каждый раз по-разному )
$(document).ready(function() {
$('.services-link').each( function(){
if ($(this).hasClass('active')){
$('.blackimg', this).hide();
$('.whiteimg', this).show();
} else {
$('.blackimg', this).show();
$('.whiteimg', this).hide();
}
})
});
.services-link .blackimage {display: block}
.services-link.active .blackimage {display: none}
.services-link .whiteimage {display: none}
.services-link.active .whiteimage {display: block}
// но тесты проходит
function repairCase(src, input) {
const len = input.length;
if (len === 0) return '';
const _src = src.toLowerCase();
const _input = input.toLowerCase();
let i, from = 0, maxWeight = -1, maxIndex = -1;
while (i = _src.indexOf(_input, from), -1 !== i) {
from = i + 1;
const match = src.substr(i, len);
let weight = 0;
for (let k = 0; k < len; k++) if (match[k] === input[k]) weight++;
if (maxWeight < weight) {
maxWeight = weight;
maxIndex = i;
}
}
if (-1 === maxIndex) return '';
return src.substr(maxIndex, len);
}
const countries = people.map(el => el.country);
people.filter((el, index) => countries.indexOf(el.country) === index)
/* [
{"id":73334,"country":"Sweden"},
{"id":73335,"country":"England"},
{"id":45445,"country":""}, // про пустые и отсутсвующие страны надо уточнить
{"id":4544500},
{"id":88989,"country":"France"}
]
*/
function groupProps(obj) {
const sums = {};
const result = {};
for (let p in obj) {
const key = p.substring(0, 4); // группируем по первым 4 символам
if (!sums.hasOwnProperty(key)) {
sums[key] = 0;
result[p] = 0;
}
sums[key] += obj[p];
}
for (let p in result) {
const key = p.substring(0, 4);
result[p] = sums[key];
}
return result;
}
groupProps(obj) // {"12345":3,"12356":2,"12360":1}