forEach is not a function

问题描述

在写一个递归方法后发现一个问题,该递归方法在一个watch监听字段中调用,于是就报了如下错误:

Error in callback for watcher 'filterTxt'. list.forEach is not a function

问题解决

第一个callback的问题可能是监听世间延迟的问题,可以在watch中调用方法的地方使用setTimeout解决。
第二个问题是递归过程中传入的参数不是数组导致的。
解决了递归的问题,第一个callback的问题也好了。递归过程中第一次传入的是数组,第二次传入的如果是类数组也会有同样的问题,所以必须慎重。
如果是类数组可以考虑转化成数组在使用forEach

filterOption() {
  let label = this.props.label
  let id = this.props.value
  let option = []
  const getOption = list => {
    list.forEach(item => {
      if (item[label].includes(this.filterText)) {
        option.push({label: item[label], value: item[id]})
        if (item.children) {
          getOption(item.children) // 出错的地方在这里 错误的直接传了item导致的 getOption(item)
        }
      }
    })
  }

  getOption(this.data)
  this.options = option
},

备注

const parent = this.el.parentElement; // 这是一个类数组的node节点集合,此时不可直接使用forEach

Array.prototype.forEach.call(parent.children, child => {
  console.log(child)
});
原文地址:https://www.cnblogs.com/codebook/p/14220334.html