基础api
-
自身屁股后面加东西:
push(a,b,...) ,返回长度
-
自身屁股后面弹东西:
pop(), 返回弹出项。
注意:空数组和undefined项均弹出undefined,使用时需判断
-
自身嘴巴前面加东西
unshfit(a,b,...), 返回长度
-
自身嘴巴前面弹东西
shift(), 返回弹出项。
undefined的问题同pop()
-
反转顺序(也是改自身)
reverse()
-
splice
自身的增,删,都能实现
splice(startIndex, num, addItem1, addItem2...)
-
实现事件监听事件触发
const evetBus = { arrays: { click: [], scroll: [] }, on: function(type, fn) { this.arrays[type] = this.arrays[type] || [] this.arrays[type].push(fn) }, off: function(type, fn) { const arrFn = this.arrays[type] if (!arrFn) return const idx = arrFn.indexOf(fn) arrFn.splice(idx,1) }, emit: function(type, data) { const arrFn = this.arrays[type] if (!arrFn) return arrFn.map(item => item(data)) } } const fn = (data) => { console.log(data) } evetBus.on('click', fn) evetBus.emit('click', 'd急急急ddd') // evetBus.off('click', fn)
示例
-
lazyMan实现按顺序执行
const lazyMan = function (name) { const array = []; const fn = () => { console.log("this is", name); next(); }; array.push(fn); // 前面任务执行完了,呼叫下一个执行:任务队列 const next = () => { const fn = array.shift(); fn && fn(); }; setTimeout(() => { next(); }, 0); const api = { sleep: (num) => { array.push(() => { setTimeout(() => { console.log("wake up", num); next(); }, num * 1000); }); return api; }, eat: (content) => { array.push(() => { console.log("eat", content); next(); }); return api; }, sleepFirst: (num) => { array.unshift(() => { setTimeout(() => { console.log("wake up", num); next(); }, num * 1000); }); return api; }, }; return api; };
感想:
-
任何需求: if...else for 都能实现
-
任何数据: 数组(有顺序) 对象(没顺序)
-
任何逻辑: 函数
-
前端内存: 一个用户在客户端上用js,不用太关心内存用的太多。后端是几万用一个服务器,内存非常重要。