問題描述
在寫一個遞歸方法后發現一個問題,該遞歸方法在一個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)
});