function toMatrix(arr) {
const len = arr.length;
const side = Math.ceil( Math.sqrt(len));
if( side * side - len !== 1) throw "Bad array length";
let result = [], index;
for(let row = 0; row < side; row++) {
result.push([]);
let currentRow = result[result.length - 1];
for(let col = 0; col < side; col++) {
index = side * row + col;
if(index > len) break;
if(index === len) {
currentRow.push(0);
} else {
currentRow.push(arr[index]);
}
}
}
return result;
}
toMatrix([1,2,5]) // [[1,2],[5,0]]
toMatrix([1,2,3,4,5,6,7,8]) // [[1,2,3],[4,5,6],[7,8,0]]
function toMatrix(arr) {
const len = arr.length;
const side = Math.ceil( Math.sqrt(len));
if( side * side - len !== 1) throw "Bad array length";
let result = [];
for(let row = 0; row < side; row++) {
result.push( arr.slice(side * row, side * (row+1))); // выкусываем подряд строку, side элементов
}
result[side - 1].push(0); // в последниюю строку дописываем 0
return result;
}
toMatrix([1,2,5]) // [[1,2],[5,0]]
toMatrix([1,2,3,4,5,6,7,8]) // [[1,2,3],[4,5,6],[7,8,0]]
значение_поля_внутреннего_объекта: ключ_внешнего_объекта
var house = {}; // внешний объект
var names = {}; // доп. словарь для поиска
function add(num, flat) {
house[num] = flat; // добавили внутренний объект
names[flat.name] = num; // запись для поиска в словарь
}
add(11, {name:"Vasya", phone:"555-111", area:111, price:1111});
add(22, {name:"Lena", phone:"555-222", area:222, price:2222});
names["Lena"] // 22
function get(name) {
return house[ names[name]];
}
get("Lena") // {name:"Lena", phone:"555-222", area:222, price:2222}
значение_поля: сам_внутренний_объект
var myEvent = new Event('teaTime');
Остается положить конверт на нужный столик: document.getElementById('stolik').dispatchEvent(myEvent);
var event = new CustomEvent('saySomething', { detail: "Hello there!" });
results
.data.results.forEach( film => {
:hover
$('.sounds-wrapper').on('mouseenter', function() {
$(this).addClass('sounds-wrapper-active');
});
$('.sounds-wrapper').on('mouseleave', function() {
$(this).removeClass('sounds-wrapper-active');
});
.sounds-wrapper { ... }
.sounds-wrapper:hover { ... здесь то, что раньше было в .sounds-wrapper-active }
var context = this;
var calina = {
write: function() {
for(var prop in context) {
if(context[prop] !== this) continue;
console.log("Found self:", prop);
return prop;
}
}
}
calina.write(); // 'calina'
context
а «искать себя» в объекте window
:var calina = {
write: function() {
for(var prop in window) {
if(window[prop] !== this) continue;
console.log("Found self:", prop);
return prop;
}
}
}
calina.write(); // 'calina'
var calina2 = calina;
Предусмотрите этот случай и собирайте/возвращайте массив значений в таком случае. function getData(html) {
var table = document.createElement('table');
table.innerHTML = html;
var tds = table.querySelectorAll('td');
var values = [], i;
for(i=0; i<tds.length; i++)
values.push(tds[i].innerText);
return values;
}
var html = [
'<tr data-user="12345" data-start="01">'
,'<td class="text-truncate success" style="font-weight:600">543210</td>'
,'<td class="text-truncate" style="font-weight:600">350 S</td>'
,'<td class="text-truncate success" style="font-weight:600">352.00 S</td>'
,'</tr>'
].join('\n');
var values = getData( html);
var var1 = values[1]; // 350 S
var var2 = values[2]; // 352.00 S
var clickCount = 0;
$('.arrow').on('click', function(){console.log( ++clickCount);});
function update(){
var previous = clickCount;
setInterval(function(){
if( clickCount === previous) return;
previous = clickCount;
if( clickCount === 1) {
console.log('С почином!');
} else if( clickCount === 2) {
console.log('Парочка!');
} else if( clickCount === 4) {
console.log('Квадроцикл');
} else if( clickCount > 5) {
console.log('Да хватит уже..');
}
}, 100);
}
update();
var el = document.createElement("script");
el.src = "https://code.jquery.com/jquery-3.3.1.min.js";
el.async = true;
el.crossorigin="anonymous";
document.body.appendChild(el);
current = current.setHours(21)
сделайте просто current.setHours(21)
(function(selector){ // ДОБАВЛЕНО
var done = false; // ДОБАВЛЕНО
function sAnim(el, fun, offset = 0) {
let self = document.querySelectorAll(el);
let winScrollY = window.scrollY;
let winHeight = window.innerHeight;
for (var i = 0; i < self.length; i++) {
let el = self[i];
let pos = el.getBoundingClientRect().top;
let top = pos.top + pageYOffset;
if (winScrollY > top - winHeight + winHeight / 100 * offset && winScrollY - winHeight < top - winHeight) {
//Нужно выполнить только 1 раз
if(done) return; // ДОБАВЛЕНО
fun(el);
done = true; // ДОБАВЛЕНО
}
}
}
function showHuntInSelecter(el) {
el.classList.add('show-hint');
setTimeout(function() {
el.classList.remove('show-hint');
}, 4000)
}
var scroll = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.msRequestAnimationFrame || window.oRequestAnimationFrame ||
function(callback) {
window.setTimeout(callback, 1000 / 60)
};
var lastPosition = -1;
function loop() {
if (lastPosition == window.pageYOffset) {
scroll(loop);
return false;
} else lastPosition = window.pageYOffset;
// Функции при скролле
sAnim(selector, showHuntInSelecter, 30); // РЕДАКТИРОВАНО
// Функции при скролле
scroll(loop);
};
loop();
})('.selecter') // ДОБАВЛЕНО
var D = new Date();
D.setDate(1);
D.setMonth(7); // 0: Янв, 1: Фев, ... 7: Август
D.setHours(12); // опционально
D.setMinutes(0); // опционально
D.setSeconds(0); // опционально
if(D.getTime() > new Date().getTime()) D.setFullYear( D.getFullYear() - 1);
D.toString() // Tue Aug 01 2017 12:00:00 GMT+0300 (MSK)
// и можно из Даты создать объект moment:
var m = moment(D);
function noExp(n){
var data= String(n).split(/[eE]/);
if(data.length== 1) return data[0];
var z= '', sign= this<0? '-':'',
str= data[0].replace('.', ''),
mag= Number(data[1])+ 1;
if(mag<0){
z= sign + '0.';
while(mag++) z += '0';
return z + str.replace(/^\-/,'');
}
mag -= str.length;
while(mag--) z += '0';
return str + z;
}
noExp(n) // String "0.0000000975"