第一種寫法:
const LazyMan = function (name) {
const array = []
const fn = () => { console.log("Hi! This is " name '!'); next() }
const next = () => {
const fn = array.shift()
fn && fn()
// array.shift() && array.shift()()
}
array.push(fn)
setTimeout(() => { next() }, 0)
const api = {
sleep: (number) => {
array.push(() => {
setTimeout(() => { console.log('Wake up after ' number); next() }, number * 1000)
})
return api
},
eat: (content) => {
array.push(() => {
console.log('eat ' content); next()
})
return api
},
sleepFirst: (number) => {
array.unshift(() => {
setTimeout(() => { console.log('Wake up after ' 5); next() }, number * 1000)
})
return api
}
}
return api
}
LazyMan("Hank").sleep(2).eat("dinner").sleepFirst(1);
// Wake up after 5
// Hi! This is Hank!
// Wake up after 2
// eat dinner
第二種寫法:
const LazyMan = function (name) {
const array = []
const fn = () => { console.log("Hi! This is " name '!'); next() }
const next = () => {
const fn = array.shift()
// fn && fn()
array.shift() && array.shift()()
}
array.push(fn)
setTimeout(() => { next() }, 0)
const api = {
sleep: (number) => {
array.push(() => {
setTimeout(() => { console.log('Wake up after ' number); next() }, number * 1000)
})
return api
},
eat: (content) => {
array.push(() => {
console.log('eat ' content); next()
})
return api
},
sleepFirst: (number) => {
array.unshift(() => {
setTimeout(() => { console.log('Wake up after ' number); next() }, number * 1000)
})
return api
}
}
return api
}
LazyMan("Hank").sleep(2).eat("dinner").sleepFirst(1);
// Wake up after 2
const fn = array.shift() fn && fn(); array.shift() && array.shift()();
第一種方法和第二種方法的控制臺輸出結果不一致,第二種方法只輸出“Wake up after 2”的結果,這不是我想要的,我想知道為什么?
uj5u.com熱心網友回復:
shift修改陣列,將其長度縮小 1 并回傳陣列的頭部。所以用你的第一個代碼:
const fn = array.shift()
fn && fn()
您呼叫 shift 一次,并將第一個函式分配給fn。您檢查 fn 是否存在,如果存在則呼叫它。該陣列現在比以前少了 1 個條目。
您的備用代碼呼叫移位 3 次:
const fn = array.shift()
array.shift() && array.shift()()
陣列的第一個元素被分配給fn,然后從未使用過。陣列的第二個元素決定是否執行&&,陣列的第三個元素是被呼叫的元素(如果不存在則拋出例外)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/392441.html
標籤:javascript
