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
*/