首页 > 解决方案 > 将参数传递给 map()

问题描述

我正在尝试在map()Array.from () 上使用内置函数,该函数使用 Puppeteer 返回一些元素。

以下是代码:

let res = await page.evaluate(elementPath => {
  return Array.from(document.querySelectorAll(elementPath), (cin, index) => {
    return {
      cs: `state is ${this.s}`, // returns state is undefined
      cinemaIndex: index,
      cinemaId: cin.getAttribute('data-id'),
      cinemaName: cin.getAttribute('data-name'),
      cinemaURL: cin.getAttribute('data-url'),
    };
  }, {
    s: 'NSW'
  });
}, `div[data-state=${cinemaState}] div.top-select-option a.eccheckbox`, cinemaState);

我无法分配cs变量scinemaState.

想知道你有没有解决办法

标签: javascriptnode.jsgoogle-chrome-devtoolspuppeteerheadless-browser

解决方案


您可以使用以下方法分配s给语句中的cinemaState属性:return

cinemaState: this.s,

此外,Array.from()它有一个内置map函数,因此您应该map从内部调用该函数Array.from()以避免中间数组:

Array.from(arrayLike, mapFn);     // good
Array.from(arrayLike).map(mapFn); // bad

cinemaState最后,您可能希望在模板文字选择器字符串中的属性选择器中使用引号:

[data-state="${cinemaState}"] // good
[data-state=${cinemaState}]   // bad

您的最终代码应如下所示:

let res = await page.evaluate(elementPath => {
  return Array.from(document.querySelectorAll(elementPath), (cin, index) => {
    return {
      cinemaState: this.s,
      cinemaIndex: index,
      cinemaId: cin.getAttribute('data-id'),
      cinemaName: cin.getAttribute('data-name'),
      cinemaURL: cin.getAttribute('data-url'),
    };
  }, {
    s: 'NSW'
  });
}, `div[data-state=${cinemaState}] div.top-select-option a.eccheckbox`, cinemaState);

推荐阅读