某公司 1 到 12 月份的销售额存在一个对象
某公司 1 到 12 月份的销售额存在一个对象里面 如下:{1:222, 2:123, 5:888},请把数据处理为如下结构:[222, 123, null, null, 888, null, null, null, null, null, null, null]
解答:
function convert(obj) {
return Array.from({ length: 12 }).map((item, index) => obj[index] || null).slice(1);
}
LazyMan
类
要求设计 LazyMan 类,实现以下功能。
LazyMan('Tony');
// Hi I am Tony
LazyMan('Tony').sleep(10).eat('lunch');
// Hi I am Tony
// 等待了10秒...
// I am eating lunch
LazyMan('Tony').eat('lunch').sleep(10).eat('dinner');
// Hi I am Tony
// I am eating lunch
// 等待了10秒...
// I am eating diner
LazyMan('Tony').eat('lunch').eat('dinner').sleepFirst(5).sleep(10).eat('junk food');
// Hi I am Tony
// 等待了5秒...
// I am eating lunch
// I am eating dinner
// 等待了10秒...
// I am eating junk food
解答:
class LazyManClass {
constructor(name) {
this.name = name;
this.fns = [];
console.log(`Hi I am ${this.name}`);
setTimeout(() => {
this.next();
});
return this
}
sleep(time) {
const fn = () => {
setTimeout(() => {
console.log(`等待了${time}秒...`)
this.next();
}, time * 1000)
}
this.fns.push(fn);
return this;
}
sleepFirst(time) {
const fn = () => {
setTimeout(() => {
console.log(`等待了${time}秒...`)
this.next();
}, time * 1000)
}
this.fns.unshift(fn);
return this;
}
eat(food) {
const fn = () => {
console.log(`I am eating ${food}`);
this.next();
}
this.fns.push(fn);
return this;
}
next() {
const fn = this.fns.shift();
fn && fn();
}
}
const LazyMan = (name) => {
return new LazyManClass(name);
}
// LazyMan('Tony');
// Hi I am Tony
// LazyMan('Tony').sleep(10).eat('lunch');
// Hi I am Tony
// 等待了10秒...
// I am eating lunch
// LazyMan('Tony').eat('lunch').sleep(10).eat('dinner');
// Hi I am Tony
// I am eating lunch
// 等待了10秒...
// I am eating diner
LazyMan('Tony').eat('lunch').eat('dinner').sleepFirst(5).sleep(10).eat('junk food');
// Hi I am Tony
// 等待了5秒...
// I am eating lunch
// I am eating dinner
// 等待了10秒...
// I am eating junk food
Q.E.D.