JavaScript forEach和Map函数的区别

一个人想着一个人 提交于 2020-02-08 04:44:27
JavaScript forEach和Map函数的区别

因为本人更喜欢使用Map函数,所以当今天遇到了一个需求就必须使用forEach,需求是这样的,判断数组中是否有重复的内容,因为我们要定义一个空数组所以,如果Map函数遍历空数组是会报错的,所以我选择了forEach函数

onDoubleClick(e) {
    if (!e.target.innerText) return;
    let targetItem = null
    if (e.target.getAttribute('labeldata')) {
      targetItem = JSON.parse(e.target.getAttribute('labelData'));
    } else {
      targetItem = e.target.innerText.replace(/,/g, '');
    }
    console.log(e.target);
    console.log(targetItem);
    let visible = false;
    let type = null;
    let activeItem = null;
    const { panes } = this.state;
    console.log(panes)
    if (typeof targetItem === 'object') {
      if (targetItem.card_num || targetItem.bank_acct) {
        visible = true;
        type = 'num'
        activeItem = targetItem;
      } else if (targetItem.branch_num || targetItem.teller_code) {
        visible = true;
        type = 'trxLocLabels'
        activeItem = targetItem;
      } else if (targetItem.code) {
        console.log(targetItem.code)
        visible = true;
        type = 'code'
        activeItem = targetItem.code;
      }
    } else {
      // if (isPhoneNumber(targetItem) || isShortNum(targetItem)) {
      //   visible = true;
      //   type = isPhoneNumber(targetItem) ? 'num' : 'shortNum';
      //   activeItem = targetItem;
      // } else if (isEventTime(targetItem)) {
      //   visible = true;
      //   type = 'time';
      //   activeItem = targetItem;
      // } else if (isCellTowerCode(targetItem)) {
      //   visible = true;
      //   type = 'code';
      //   activeItem = targetItem;
      // }
    }

    if (!visible) return;
    panes.forEach((item, index) => {//forEach为空数组时不报错
      console.log(panes)
      if (typeof activeItem === 'object' && typeof item.activeItem === 'object') {
        if (JSON.stringify(item.activeItem) === JSON.stringify(activeItem)) {
          panes.splice(index, 1);
        }
      } else if (item.activeItem === activeItem) {
        panes.splice(index, 1);
      }
    });
    let zIndex = this.props.globalLabels.zIndex + 1;
    this.props.actions.addZindexGlobalLabel(zIndex)
    panes.push({
      visible,
      type,
      activeItem,
      zIndex
    });
    this.setState({
      panes,
    });
  }

两者的区别:(两者的参数都是一致的,回调函数的参数也是一样的)
1、forEach()返回值是undefined,不可以链式调用。
2、map()返回一个新数组,原数组不会改变。callback参数返回的值就是数组中的新元素。

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!