function throttle(f, delay) {
let lastCall = -Infinity;
return function() {
const now = +new Date;
if (now - lastCall > delay) {
lastCall = now;
return f.apply(this, arguments);
}
};
}
date_create(2019-05-16)
$keys = array_keys($arr);
$head = "<tr><th>year</th>".implode("", array_map(function($n) {
return "<th>$n</th>";
}, $keys))."</tr>";
$rows = implode("", array_map(function($key) use($arr) {
return "<tr><td>$key</td>".implode("", array_map(function($n) use($key) {
return "<td>$n[$key]</td>";
}, $arr))."</tr>";
}, array_keys($arr[$keys[0]])));
echo "<table>$head$rows</table>";
Object.entries(props).filter(n => n[1]).map(n => n[0]).join(',')
// или
`${Object.entries(props).reduce((acc, [ k, v ]) => (v && acc.push(k), acc), [])}`
// или
Object.entries(props).map(n => n[1] && n[0]).filter(Boolean).toString()
// или
'' + Object.keys(props).reduce((acc, n) => props[n] ? [ ...acc, n ] : acc, [])
// или
String(Object.keys(props).filter(n => props[n]))
let arrays: [[String]] = [array1, array2]
var combinations: [[String]] = []
let arraysLen: Int = arrays.count
let arrLen: Int = arrays[0].count
let numCombinations: Int = Int(pow(Double(arraysLen), Double(arrLen)))
for i in (0 ..< numCombinations) {
var combination: [String] = []
for j in (0 ..< arrLen) {
let arrIndex: Int = i / Int(pow(Double(arraysLen), Double(j))) % arraysLen
let elIndex: Int = arrLen - j - 1
combination.insert(arrays[arrIndex][elIndex], at: 0)
}
combinations.append(combination)
}
const key = 'background-color';
const values = [ 'red', 'lime', 'yellow', 'aqua', 'brown', 'magenta' ];
const getValue = i => values[i % values.length];
const selector = '.item';
$(selector).css(key, getValue);
// или
document.querySelectorAll(selector).forEach((n, i) => {
n.style[key] = getValue(i);
// или
n.style.setProperty(key, getValue(i));
// или
n.style.cssText += `${key}: ${getValue(i)}`;
// или
n.setAttribute('style', key + ': ' + getValue(i));
});
this.sliderPoint.on('click', e => {
this.currentImg = e.target.dataset.id;
this.scrollImages(this.currentImg, this.speed);
});
[...Array(count)]
.map((n, i) => `<div class="slider-point" data-id="${i}"></div>`)
.join('')
// или
''.concat(...Array.from(
{ length: count },
(n, i) => '<div class="slider-point" data-id="' + i + '"></div>'
))
Array(count).fill('<div class="slider-point"></div>').join('')
// или
Array(-~count).join('<div class="slider-point"></div>')
// или
'<div class="slider-point"></div>'.repeat(count)
this.currentImg = $(e.target).index();
// или
this.currentImg = [...e.target.parentNode.children].indexOf(e.target);
user() {
return new Proxy(this.$store.state.user, {
set: (target, prop, value) => {
this.$store.commit('updateUser', { [prop]: value });
return true;
},
});
},
updateUser(state, payload) {
Object.assign(state.user, payload);
},
document.addEventListener('click', e => {
const slide = e.target.closest('.slide');
if (slide) {
const index = Array.prototype.indexOf.call(
slide.parentNode.children,
slide
);
console.log(index);
}
});
for (const n of document.querySelectorAll('.slide')) {
n.addEventListener('click', onClick);
}
function onClick() {
let index = 0;
for (let el = this; el = el.previousElementSibling; index++) ;
console.log(index);
}
document.querySelectorAll('.slider').forEach(function({ children }) {
[].forEach.call(children, (n, i) => {
n.dataset.index = i;
n.addEventListener('click', this);
});
}, e => console.log(+e.currentTarget.dataset.index));
const slidesCount = this.slider.find('.slide').length;
// или
const { length: slidesCount } = this.slider.children();
const dotHTML = '<div class="slider-point"></div>';
const dotsHTML = Array(slidesCount).fill(dotHTML).join('');
// или
const dotsHTML = Array(slidesCount + 1).join(dotHTML);
// или
const dotsHTML = dotHTML.repeat(slidesCount);
this.slider.siblings('.slider-pagination').append(dotsHTML);
// или
this.slider.closest('.slider-box').find('.slider-pagination').html(dotsHTML);
beforeMount() { // какой тут хук использовать? const fields = ['input1', 'input2'] fields.forEach(item => this[item] = '') // я правильно добавляю в this, а не в this.$data? }
Объект с данными, над которым экземпляр Vue осуществляет наблюдение. Экземпляр проксирует сюда вызовы своих полей. (Например,vm.a
будет указывать наvm.$data.a
)
Vue не может обнаружить добавление или удаление свойства. Так как Vue добавляет геттер/сеттер на этапе инициализации экземпляра, свойство должно присутствовать в объектеdata
для того чтобы Vue преобразовал его и сделал реактивным.
<...>
Во Vue нельзя динамически добавлять новые корневые реактивные свойства в уже существующий экземпляр.
data: () => ({
inputs: Array(20).fill(''),
}),
<div v-for="(n, i) in inputs">
Значение #{{ i }}:
<input v-model="inputs[i]">
{{ n }}
</div>
this.previousImage = this.previousImage.bind(this);
this.nextImage = this.nextImage.bind(this);
this.prevBtn = this.slider.siblings(".slider-btn.previous");
this.nextBtn = this.slider.siblings(".slider-btn.next");
if($(this).children().is(':checked')){ $(this).addClass('active'); } else { $(this).removeClass('active'); }
$(this).addClass('active').siblings().removeClass('active');
const groupQuestions = arr => ({
testId: arr[0].testId,
questions: Object.values(arr.reduce((acc, n) => {
const id = n.questionId;
(acc[id] = acc[id] || {
questionId: id,
questionText: n.questionText,
answers: [],
}).answers.push({
answer: n.answer,
isRight: n.isRight,
});
return acc;
}, {})),
});
const data = [
{
floors: [ 1 ],
limits: [
{ f: 1.26, max: 120 },
{ f: 1.24, max: 140 },
{ f: 1.23, max: 160 },
{ f: 1.22, max: 200 },
{ f: 1.20, max: 260 },
{ f: 1.19, max: 300 },
],
},
{
floors: [ 2, 3 ],
limits: [
{ f: 1.00, max: 100, excludeMax: true },
{ f: 1.30, max: 130 },
{ f: 1.27, max: 160 },
{ f: 1.24, max: 200 },
{ f: 1.22, max: 300 },
],
},
];
const d = data.find(n => n.floors.includes(floors.value));
if (d) {
const v = area.value;
console.log((d.limits.find(n => n.excludeMax ? n.max > v : n.max >= v) || { f: 1 }).f);
}