在computed中使用forEach会报 "TypeError: [] is not a function" 这个错误
computed: {
...mapState(namespace, {
countingTask: (state) => state.countingTask
}),
countingTaskCheckWarehouse () {
let warehouse = []
(this.countingTask.checkWarehouse || []).forEach((item) => {
warehouse.push(item.name)
})
let warehouseStr = warehouse.join(',')
return warehouseStr
}
}
解决方案:
- 使用 for
computed: {
...mapState(namespace, {
countingTask: (state) => state.countingTask
}),
countingTaskCheckWarehouse () {
let warehouse = []
for (let i = 0; i < this.countingTask.checkWarehouse.length; i++) {
warehouse.push(this.countingTask.checkWarehouse[i].name)
}
let warehouseStr = warehouse.join(',')
return warehouseStr
}
}
- 使用 for...of...
computed: {
...mapState(namespace, {
countingTask: (state) => state.countingTask
}),
countingTaskCheckWarehouse () {
let warehouse = []
for (let item of this.countingTask.checkWarehouse) {
warehouse.push(item.name)
}
let warehouseStr = warehouse.join(',')
return warehouseStr
}
}
- 使用 map
computed: {
...mapState(namespace, {
countingTask: (state) => state.countingTask
}),
countingTaskCheckWarehouse () {
return (this.countingTask.checkWarehouse || []).map(x => x.name).join(',')
}
},