返回不是在JavaScript forEach函数中发生吗?

时间:2019-11-18 18:41:57

标签: javascript function return

我正在使用DocxJS包创建文档。在我的文档中,我试图创建一个函数,该函数将迭代一些前端道具并为数组中的每个对象创建多个段落。每当我遍历数组并进行console.log记录时,它就可以正常工作。当我做同样的事情并尝试使用return语句按照文档中的说明编写“新段落”时,它无法正常工作,并且不返回任何内容。

以下是软件包和文档: 包裹:https://www.npmjs.com/package/docx 文档:https://docx.js.org/#/

我的数组标记如下:

[{item}, {item}, {item}]

数组中的对象是:

{item.value, item.description, item.tags}

这是我创建的函数:

const createItem = () => {
    let itemArray = this.props.goods.products.items;
    console.log(itemArray);

    // This will properly console.log the item description for each one (3 total)
    itemArray.forEach((item) => {
        console.log(item.description);
    })

    // This doesn't return anything, but the console.log DOES return the item descriptions like before
    itemArray.forEach((item) => {
         return new Paragraph({
             text: `${item.description}`,
             alignment: AlignmentType.CENTER,
             style: 'educationDegree'
         }, console.log(item.description));
    })
}

在我使用docx软件包创建的文档中,我只是像这样调用函数:createItem()

我尝试传递createItem(this.props.goods.products.items),但它什么也没做。我试着做:this.createItem(this.props.goods.products.items),它只是返回this.createItem不是函数。

我只是不知道为什么它不能正常工作,并在遍历数组时返回每个项目的item.description?当前,除了我请求的控制台日志外,它什么都不返回。

2 个答案:

答案 0 :(得分:2)

类似的东西应该对您有用:

const itemArray = [{description: 'Lorem ipsum'}, {description: 'Lorem ipsum'}]

const AlignmentType = {
   CENTER: 'center'
}

class Paragraph {
  constructor(text, alignment, style) {
    this.text = text
      this.alignment = alignment
      this.style = style
  }
}

const paragraphArray = itemArray.reduce((acc, item) => [...acc, new Paragraph(item.description, AlignmentType.CENTER, 'educationDegree')],[])

答案 1 :(得分:0)

Array.prototype.forEach()始终返回void,无论使用Array.prototype.reduce()还是编写自定义函数以接收一个数组并返回一个新数组(而不是对您传递的数组的引用),无论可以参考mdn MDN Array

您会看到文档中提到forEach的返回值始终是未定义的,我建议您使用Array.prototype.reduce()

   let resArr = itemArray.reduce((acc,item) =>{
             let para = new Paragraph({
                 text: `${item.description}`,
                 alignment: AlignmentType.CENTER,
                 style: 'educationDegree'
             })
             acc.push(para)
             return acc;
        },[]);

优良作法是获取新对象,而不是对现有的引用对象进行突变,因此认为这样做会有所帮助。