如何使用JavaScript在Map中删除此类元素?

时间:2019-09-26 18:59:23

标签: javascript

function Stream() {
  let subscriber = new Map();

  return {
      subscribe: function(method) {
        if(typeof method === 'function') {
          subscriber.set(method);
        }
        else
          throw new Error('Pass a valid method.');
      },
      push: function(val) {
        [...subscriber].forEach(([method]) => method(val));
      },
      unsubscribe: function(method) {
        console.log(subscriber.has([method]));
        console.log([method]);
        [...subscriber].forEach(([method]) => console.log([method]));
        if (typeof method === 'function' && subscriber){
          subscriber.delete([method]);
        }
        [...subscriber].forEach(([method]) => console.log([method]));
      }
  };
}

var stream = new Stream();
stream.subscribe((val)=>console.log(val*1));
stream.subscribe((val)=>console.log(val*2));
stream.subscribe((val)=>console.log(val*3));

stream.push(2);
stream.push(3);
stream.unsubscribe((val)=>console.log(val*3));
stream.push(4);

在unsubscibe函数中,该函数显示“ subscriber.has([method])”向我返回false,但是在我打印出该方法并与订户映射的一侧进行比较之后,它看起来相同。这里有什么问题吗?

1 个答案:

答案 0 :(得分:1)

您有两个主要问题。

首先,.has()的参数应该仅为method,而不是[method]。键subscribers只是函数,而不是数组。您写过[method]的所有地方都不应该放在数组中。

第二,您需要使用命名函数。具有相同源代码的两个函数实际上并不相等,因此.has()将无法匹配它们。

您应该使用Set而不是Map,因为您没有将任何值与函数相关联。无需使用[...subscriber]MapSet都具有forEach遍历元素的方法。

console.log(((val)=>console.log(val*3)) == ((val)=>console.log(val*3)))

将记录false

function Stream() {
  let subscriber = new Set();

  return {
      subscribe: function(method) {
        if(typeof method === 'function') {
          subscriber.add(method);
        }
        else
          throw new Error('Pass a valid method.');
      },
      push: function(val) {
        subscriber.forEach((method) => method(val));
      },
      unsubscribe: function(method) {
        console.log(subscriber.has(method));
        console.log(method);
        subscriber.forEach((method) => console.log(method));
        if (typeof method === 'function' && subscriber){
          subscriber.delete(method);
        }
        subscriber.forEach((method) => console.log(method));
      }
  };
}

var stream = new Stream();
const times1 = (val)=>console.log(val*1);
stream.subscribe(times1);
const times2 = (val)=>console.log(val*2);
stream.subscribe(times2);
const times3 = (val)=>console.log(val*3)
stream.subscribe(times3);

stream.push(2);
stream.push(3);
stream.unsubscribe(times3);
stream.push(4);