将参数传递给 map()

Passing arguments into map()

我正在尝试在 Array.from () 上使用内置的 map() 函数,returns 某些元素使用 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

想知道您是否有解决方案

[1,2,3,4].map(function(num, index,wholeArray){
    console.log(num,index,wholeArray,this.s);
},{s:"nsw"})

maps 有两个参数 callbackthisArg 无论你将在第二个参数传递什么都可以访问 bi this

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

cinemaState: this.s,

此外,Array.from() has a built-in map function, so you should call the map function from within 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);

这个我可以解释。这对我有用。我不得不将箭头函数替换为传统函数

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);