setTimeout
Javascript執(zhí)行引擎的主線程運(yùn)行的時候,產(chǎn)生堆(heap)和棧(stack)。程序中代碼依次進(jìn)入棧中等待執(zhí)行,當(dāng)調(diào)用setTimeout()方法時,瀏覽器內(nèi)核相應(yīng)模塊開始延時方法的處理,當(dāng)延時方法到達(dá)觸發(fā)條件時,方法被添加到用于回調(diào)的任務(wù)隊列,只有執(zhí)行引擎棧中的代碼執(zhí)行完畢,主線程才會去讀取任務(wù)隊列,依次執(zhí)行那些滿足觸發(fā)條件的回調(diào)函數(shù)。
如果setTimeout加入隊列的阻塞時間大于兩個setTimeout執(zhí)行的間隔時間,那么先加入任務(wù)隊列的先執(zhí)行,盡管它里面設(shè)置的時間比另一個setTimeout的要大。
栗子1
Time2先執(zhí)行,因為阻塞的時間大于兩個setTimeout之間的間隔時間。
//Time2
setTimeout(function () {
console.log(2)
}, 400)
const start = new Date()
for (let i = 0; i < 5000; i++) {
console.log('這里只是模擬一個耗時操作')
}
const end = new Date()
console.log('阻塞耗時:' + Number(end - start) + '毫秒')
//Time1
setTimeout(function () {
console.log(3)
}, 300)
栗子2
我們把for循環(huán)里面的時間設(shè)置短一點:
setTimeout(function () {
console.log(2)
}, 400)
const start = new Date()
for (let i = 0; i < 500; i++) {
console.log('這里只是模擬一個耗時操作')
}
const end = new Date()
console.log('阻塞耗時:' + Number(end - start) + '毫秒')
//Time1
setTimeout(function () {
console.log(3)
}, 300)
此時,Time1先執(zhí)行,因為阻塞的耗時小于Time1和Time2的執(zhí)行間隔時間100毫秒。
arguments
擁有一個length屬性和若干索引屬性的對象。
const arrayLike = {
0: 'name',
1: 'age',
2: 'sex',
length: 3
}
調(diào)用數(shù)組方法
如果類數(shù)組想用數(shù)組的方法怎么辦呢?我們可以用Function.call間接調(diào)用:
const arrayLike = {
0: 'name',
1: 'age',
2: 'sex',
length: 3
}
const arrayLike = {
0: 'name',
1: 'age',
2: 'sex',
length: 3
}
console.log(Array.prototype.slice.call(arrayLike))
類數(shù)組轉(zhuǎn)數(shù)組
const arrayLike = {0: 'name', 1: 'age', 2: 'sex', length: 3 }
// 1. slice
Array.prototype.slice.call(arrayLike) // ["name", "age", "sex"]
// 2. splice
Array.prototype.splice.call(arrayLike, 0) // ["name", "age", "sex"]
// 3. ES6 Array.from
Array.from(arrayLike) // ["name", "age", "sex"]
// 4. apply
Array.prototype.concat.apply([], arrayLike)
length屬性
Arguments對象的length屬性,表示實參的長度,舉個例子:
function foo(b, c, d){
console.log("實參的長度為:" + arguments.length)
}
console.log("形參的長度為:" + foo.length)
callee屬性
Arguments 對象的 callee 屬性,通過它可以調(diào)用函數(shù)自身。
function fibonacci(n) {
if(n < 0) {
return false
}
if(n === 0) {
return 0
} else if(n === 1) {
return 1
} else {
return arguments.callee(n - 1) + arguments.callee(n - 2)
}
}
console.log(fibonacci(3))