map 遍歷數組每一個元素並調用回調,並返回一個包含所有結果的數組。
函數聲明如下:
/**
* Calls a defined callback function on each element of an array, and returns an array that contains the results.
* @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
*/
map<U>(callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): U[];
map函數遍歷操作和調用回調函數是同步,會阻塞整個線程直到遍歷完成。如果回調函數中有異步操作,不會等異步操作完成而是往下遍歷。
如下代碼,map 的回調函數是一個同步阻塞函數阻塞線程 10 毫秒,那麼遍歷 10個成員則會阻塞主線程 100 毫秒。在這 100 毫秒內事件線程內所有的異步回調都不會被調用。下面代碼中,當 map 阻塞線程時,setInterval 的回調不會被調用,直到 map 遍歷結束。
const TestMapBlock = () => {
const blockTenMillisecond = () => {
const before = Date.now();
while (true) {
if (Date.now() > before + 10) {
console.log(`sync task finished`);
break;
}
}
};
const ls = [];
for (let i = 0; i < 10; i++) {
ls.push(i);
}
setInterval(() => {
console.log('-');
}, 1);
ls.map(blockTenMillisecond);
console.log('map finished');
};
TestMapBlock()
/*output:
sync task finished
省略8個相同的
sync task finished
map finished //遍歷完之後才執行該語句
-
// 省略多個相同的
-
*/
如下代碼 map 的回調函數中包含異步操作,map 在調用回調函數時不會阻塞,繼續往下執行,異步操作的回調直到異步完成後纔會被調用。
const MapAsyncCallback = () => {
const asyncOperation = (value: number) => {
setTimeout(() => {
console.log(`${value} async operation finished`);
}, 10);
};
const ls = [];
for (let i = 0; i < 10; i++) {
ls.push(i);
}
ls.map(asyncOperation);
setTimeout(() => {
console.log('.');
}, 1);
console.log('map finished');
};
/*
output:
map finished
0 async operation finished
1 async operation finished
2 async operation finished
3 async operation finished
4 async operation finished
5 async operation finished
6 async operation finished
7 async operation finished
8 async operation finished
9 async operation finished
*/