0

我正在尝试在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.

想知道你有没有解决办法

4

3 回答 3

0

您可以使用以下方法分配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);
于 2018-11-05T18:46:16.653 回答
0
[1,2,3,4].map(function(num, index,wholeArray){
    console.log(num,index,wholeArray,this.s);
},{s:"nsw"})

maps 有两个参数callbackthisArg无论你在第二个 arg 传递什么,都可以访问 bithis

于 2018-11-05T03:59:22.040 回答
0

我能够解释这一点。这对我有用。我不得不将箭头函数替换为传统函数

let res = await page.evaluate(elementPath => {
  return Array.from(document.querySelectorAll(elementPath), function (cin, index) // changed from (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);
于 2018-11-07T09:09:12.537 回答