写一段简单的代码来测试subscribeToArray:
test1(){
const subscribeToArray = (array) => (subscriber) => {
for (let i = 0, len = array.length; i < len; i++) {
subscriber.next(array[i]);
}
subscriber.complete();
} ;
console.log(subscribeToArray);
const input = [1, 2, 3];
const result = subscribeToArray(input);
const print = (a) => {
if(!!a){
console.log('next: ' + a);
}
else{
console.log('completed!');
}
}
const mySubscribe = {
next: print,
complete: print
};
result(mySubscribe);
执行结果:
逐一分析:
subscribeToArray是一个函数,它接收一个array,生成另一个函数。第二个函数接收一个输入参数subscriber,函数体内依次调用next和complete方法处理array的内容。
如下图所示,观察第二个函数是如何接受subscriber对象并产生输出的:
当然支持输入为多重数组:
输出:
更多Jerry的原创文章,尽在:"汪子熙":
网友评论